4

我尝试使用 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 ?

4

1 回答 1

8

您的逻辑是正确的,您的错误实际上是一个常见的 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);
  });
});
于 2015-05-08T06:10:28.157 回答