Meteor ReactiveVar - TypeError:无法调用未定义的方法'set'

时间:2015-05-08 06:06:32

标签: javascript meteor meteor-autoform meteor-helper

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

1 个答案:

答案 0 :(得分: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);
  });
});