Meteor ReactiveVar - TypeError: cannot call 'set' method from undefined

I tried using ReactiveVar. I do not know how to handle ReactiveVar. Here is the code I 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!!! Something went wrong!");
      return;
    } else {
      this.name.set(result); // TypeError: Cannot call method 'set' of undefined
      return;
    }
  });
});

Am I allowed to install and receive ReactiveVar? or How to install and get ReactiveVar ??

+4
source share
1 answer

Your logic is correct, your mistake is in fact a common lie of JS: inside the callback function, the Meteor.callscope is thischanged and no longer refers to the template instance.

You need to use Function.prototype.bindand update the code:

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));
});

You can also use a local variable captured by the closure (you'll often see this style in JS projects):

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);
  });
});
+7

All Articles