2015-05-08 16 views
4

我试过使用ReactiveVar。我不知道如何处理ReactiveVar。这里我试过的代码。Meteor ReactiveVar - TypeError:不能调用未定义的方法'set'

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?

回答

7

你的逻辑是正确的,你的错误实际上是一个常见的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); 
    }); 
}); 
+0

我不得不创建一个变量来指向Template.instance()以获得ReactiveVar的工作,var instance = Template.instance();然后在Meteor.call的回调方法中引用该“实例” –

相关问题