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


i tried use reactivevar. doesnt know how handle reactivevar. here code have tried.

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!!! went wrong!");       return;     } else {       this.name.set(result); // typeerror: cannot call method 'set' of undefined       return;     }   }); }); 

is right set , reactivevar? or how set , reactivevar ??

your logic correct, error common js pitfall : inside meteor.call callback function, this scope modified , no longer references template instance.

you need use function.prototype.bind , update code :

template.home.oncreated(function () {   this.name = new reactivevar();   meteor.call("getnames", function(error, result) {     if(error){       alert("oops!!! went wrong!");       return;     }     this.name.set(result);   // bind template instance callback `this` context   }.bind(this)); }); 

you use local variable captured closure (you'll see style in js projects) :

template.home.oncreated(function () {   // use alias `this` avoid scope modification shadowing   var template = this;   template.name = new reactivevar();   // callback going capture parent local context   // include our `template` var   meteor.call("getnames", function(error, result) {     if(error){       alert("oops!!! went wrong!");       return;     }     template.name.set(result);   }); }); 

Comments