gpt4 book ai didi

javascript - meteor ReactiveVar - TypeError : Cannot call method 'set' of undefined

转载 作者:搜寻专家 更新时间:2023-11-01 05:10:55 26 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - meteor ReactiveVar - TypeError : Cannot call method 'set' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com