【问题标题】:Meteor ReactiveVar - TypeError: Cannot call method 'set' of undefinedMeteor ReactiveVar - TypeError:无法调用未定义的方法'set'
【发布时间】:2015-07-18 22:57:21
【问题描述】:

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

【问题讨论】:

    标签: javascript meteor meteor-autoform meteor-helper


    【解决方案1】:

    你的逻辑是对的,你的错误其实是一个常见的 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);
      });
    });
    

    【讨论】:

    • 我必须创建一个变量来指向 Template.instance() 以使 ReactiveVar 工作,var instance = Template.instance();然后在 Meteor.call 的回调方法中引用那个“实例”
    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多