我尝试使用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 ??
您的逻辑正确,您的错误实际上是一个常见的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);
});
});