【问题标题】:Update reactive var with server Method使用服务器方法更新反应变量
【发布时间】:2017-05-22 20:40:00
【问题描述】:

我在客户端更新 Meteor 应用程序中的某些值时遇到问题。我试图了解 ReactiveVar 是如何工作的。 当我在客户端对集合使用 find() 方法时,每次更改某些内容时,站点都会立即更新。我想使用 ReactiveVar 和服务器端方法来达到同样的效果。所以下面的代码对我来说是正确的:

// Client
Template.body.onCreated(function appBodyOnCreated() {
  this.subscribe('activities');
}

Template.body.helpers({
  getCounter() {
    return Activities.find({
       editorId: Meteor.userId(),
       'referredObject.type': 'LIST'
   }).count();
}
});

但是当我尝试使用服务器端方法达到相同的效果时,它无法正常工作。下面的代码只更新一次变量。如果我想获取当前值,我需要刷新页面。

// Server
Meteor.methods({'activitiesCreateCount'(userId, objectType) {
    check(userId, String);
    check(objectType, String);
    return Activities.find({
        editorId: userId,
        'referredObject.type': objectType
    }).count();
} 
});

// Client

Template.body.onCreated(function appBodyOnCreated() {
  this.subscribe('activities');
  this.activitiesAmount = new ReactiveVar(false);
}

Template.body.helpers({
  getCounter() {
    var tempInstance = Template.instance();
    Meteor.call('activitiesCreateCount', Meteor.userId(), 'TODO', function(err, response) {
      tempInstance.activitiesAmount.set(response);
    });
    return Template.instance().activitiesAmount.get();
}
});

如果我希望始终拥有变量的当前值(如第一个仅客户端示例),我该如何改进我的代码?

【问题讨论】:

  • 它按预期工作。如果您有一个可行的解决方案,为什么不想使用它?
  • 假设我有一个复杂而耗时的任务。如果一个用户改变了一些东西,它应该触发这个复杂的任务,结果应该在另一个特定的用户屏幕上更新。我不确定在客户端执行这项复杂任务是否是个好主意,因此我正在尝试寻找其他解决方案。
  • 如果这个想象中的“复杂而耗时的任务”改变了某些集合中某些文档中的某些值,只需订阅它,它就会始终保持最新状态。要减少发送给客户端的数据量,请使用fields
  • 如果你还是想使用方法,你应该定义它重新运行的条件。如果你把它放在 helper 中,也可以把一些响应式数据源放到那个 helper 中,这样当这个响应式数据源发生变化时,helper 会重新运行。

标签: javascript asynchronous meteor


【解决方案1】:

尝试将Meteor.call移动到Template.body.onCreated 像这样的

  // Server
  Meteor.methods({'activitiesCreateCount'(userId, objectType) {
      check(userId, String);
      check(objectType, String);
      return Activities.find({
          editorId: userId,
          'referredObject.type': objectType
      }).count();
  } 
  });

  // Client

  Template.body.onCreated(function appBodyOnCreated() {        
    self = this;
    this.activitiesAmount = new ReactiveVar(false);
    Meteor.call('activitiesCreateCount', Meteor.userId(), 'TODO', function(err, response) {
      self.activitiesAmount.set(response);
    });
  }

  Template.body.helpers({
    getCounter() {
      return Template.instance().activitiesAmount.get();
  }
  });

【讨论】:

  • 也只运行一次。
猜你喜欢
  • 1970-01-01
  • 2021-11-22
  • 2020-01-09
  • 2018-06-01
  • 2019-07-13
  • 1970-01-01
  • 2017-12-06
  • 2021-03-07
  • 1970-01-01
相关资源
最近更新 更多