从Meteor中的onCreated访问助手

时间:2015-07-18 16:46:00

标签: javascript meteor

我有:

Template.myTemplate.helpers({
  reactiveVar: new ReactiveVar
});

如何从onCreated访问reactiveVar进行设置?

Template.restaurantEdit.onCreated(function() {
  // Access helpers.reactiveVar from here to set up
  // My goal is to set up data to reactiveVar, ex:
  helpers.reactiveVar = this.data.someData;
});

我发现有受保护的__helpers:this.view.template.__helpers

但是有没有 Meteor 访问助手的好方法?或者是Meteor从加载的data

设置reactiveVar的方法

2 个答案:

答案 0 :(得分:4)

您基本上不会直接访问Meteor中的帮助程序。如果您想将scoped reactivity与ReactiveVar一起使用,您应该这样做:

Template.restaurantEdit.onCreated(function() {
  //define all your reactive variables here
  this.reactiveVar = new ReactiveVar('default value');
});

Template.restaurantEdit.helpers({
  reactiveVar: function() {
    //access reactiveVar template variable from onCreated() hook
    return Template.instance().reactiveVar.get();
  }
});

Template.restaurantEdit.events({
  'click yourselector': function(evt, template) {
    template.reactiveVar.set('new value');
  }
});

在此处阅读有关范围反应的更多信息:https://dweldon.silvrback.com/scoped-reactivity

答案 1 :(得分:1)

您应该在onCreated()块中设置反应变量,然后通过helper访问它,反之亦然。

Template.restaurantEdit.onCreated(function(){
  this.foo = new ReactiveVar;
});

Template.restaurantEdit.helpers({
  foo: function(){
    return Template.instance().foo.get();
  }
});

只要您ReactiveVar更改,帮助程序就会更新。