Meteor ReactiveVar - TypeError: невозможно вызвать метод «набор» неопределенного

Я пытался использовать 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??


person Ramesh Murugesan    schedule 08.05.2015    source источник


Ответы (1)


Ваша логика верна, ваша ошибка на самом деле является распространенной ловушкой 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);
  });
});
person saimeunt    schedule 08.05.2015
comment
Мне пришлось создать переменную, указывающую на Template.instance(), чтобы заставить ReactiveVar работать, var instance = Template.instance(); а затем сослаться на этот экземпляр в методе обратного вызова Meteor.call - person Predrag Stojadinović; 11.09.2015