我尝试使用ReactiveVar。我不知道如何处理ReactiveVar。这是我尝试过的代码。

Template.Home.helpers({
  names: function(){
    temp = Template.instance().name.get();
    return temp;
  }
});

Template.Home.onCreated(function () {
  this.name = new ReactiveVar();
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    } else {
      this.name.set(result); // TypeError: Cannot call method 'set' of undefined
      return;
    }
  });
});

我设置并获得ReactiveVar是否正确?或如何设置和获取ReactiveVar?

最佳答案

您的逻辑是正确的,您的错误实际上是一个常见的JS陷阱:在Meteor.call回调函数中,this范围已修改,不再引用模板实例。

您需要使用Function.prototype.bind并更新您的代码:

Template.Home.onCreated(function () {
  this.name = new ReactiveVar();
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    }
    this.name.set(result);
  // bind the template instance to the callback `this` context
  }.bind(this));
});

您还可以使用由闭包捕获的局部变量(您经常会在JS项目中看到这种样式):
Template.Home.onCreated(function () {
  // use an alias to `this` to avoid scope modification shadowing
  var template = this;
  template.name = new ReactiveVar();
  // the callback is going to capture the parent local context
  // it will include our `template` var
  Meteor.call("getNames", function(error, result) {
    if(error){
      alert("Oops!!! Something went wrong!");
      return;
    }
    template.name.set(result);
  });
});

09-17 00:16