在Meteor中的onCreated中访问助手函数

3

我有:

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可以访问helpers的好方法?或者从加载的data设置reactiveVar的Meteor方式是什么?
2个回答

4

在 Meteor 中,你基本上不会直接访问 helpers。如果你想要使用作用域响应性和 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


如果你正在寻找一种响应式的访问模板数据的方式(这就是我寻找这个解决方案的原因),可以使用Template.currentData()(当然要在autorun中使用)。+1 - Rijk

1
你应该在onCreated()块中设置响应式变量,然后通过helper访问它,而不是反过来。
Template.restaurantEdit.onCreated(function(){
  this.foo = new ReactiveVar;
});

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

这个帮助器会在你的ReactiveVar更改时更新。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接