我在客户端更新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();
}
});


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

最佳答案

尝试将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();
  }
  });

07-24 09:50
查看更多