从助手获取模板数据

Get template data from helper

我正在尝试在 onCreated 挂钩上更新模板的数据上下文:

Template.segment.onCreated(function () {
  var tp = this;

  this.test = "TEST";
  Meteor.call('getTreeCategData', function (error, data) {
    tp.ExternalapiData = data;
    tp.chart = new Chart(); 
    //...
  });
});

我想将这些引用保留在父模板中,以便从子模板访问它们。

现在我 "update" 一个数据上下文,其值在 onCreated 上设置。

Template.segment.helpers({
  parentDatacontext: function(){
    this.chart = Template.instance().chart; //undefined
    this.apiData = Template.instance().apiData; //undefined
    //But it executed later, when I open the chrome object inspector    the reference, they are not undefined anymore 
    console.log("parentDatacontext: ", Template.instance());
    return this;
  }
});

我的模板:

<template name="segment">
{{#with parentDatacontext}}
{{> childtp}}
{{/with}}
</template>

最终在子模板事件的处理程序上使用它们:

Template.childtp.events({
    'click .js-close': function(e, tp){
        console.log(" tp parent data: ",Template.parentData(1));
    }
});

实际上我很快就卡在了这个过程中,我什至无法从助手打印 onCreated 上添加的属性集... 我猜助手是在创建结束之前由模板调用的...

知道如何解决这个问题,或者有更好的方法来做我想做的事吗?

谢谢

parentDataContext() 在你的 Meteor.call 回来之前被执行,然后因为你的变量不是反应性的,所以助手不会再次执行。您想要使用 reactive variable 来存储这些值,以便在方法设置值时执行助手。

要访问子模板中的新反应变量,请遵循 this forum post

ReactiveVar怎么样?

Template.segment.onCreated(function () {
  var tp = this;

  this.apiData = new ReactiveVar();
  Meteor.call('getTreeCategData', function (error, data) {
    tp.apiData.set(data);
    tp.chart = new Chart();
    //...
  });
});

Template.segment.helpers({
  parentDatacontext: function(){
    this.chart   = Template.instance().chart;
    this.apiData = Template.instance().apiData.get();

    //    data - {{with parentDatacontext}}
    // no data - {{else}}
    if (this.apiData) {
        return this;
    }
  }
});

和模板代码

<template name="segment">
    {{#with parentDatacontext}}
        {{> childtp}}
    {{else}}
        Loading or something...
    {{/with}}
</template>