【问题标题】:Get reactive var from another template in Meteor从 Meteor 中的另一个模板获取反应变量
【发布时间】:2015-07-25 17:25:27
【问题描述】:

我在 Meteor 中有一个包含一些嵌套模板的模板:

<template name="collectingTmpl">
  {{> firstTmpl}}
  {{> secondTmpl}}
</template>

如果我在firstTmpl 中设置了一个反应变量/字典

Template.firstTmpl.events({
  'click .class-name': function(event, template) {
    template.state = new ReactiveDict;
    template.state.set('someName', 'someValue');
  }
});

我可以在同一个模板中得到这个值

Template.firstTmpl.helpers({
  myValue: function() {
    Template.instance().state.get('someName');
  }
});

但是我也可以从secondTmpl 中检索firstTmpl 中设置的值吗?

我的意思是像

Template.secondTmpl.helpers({
  myValueFromAnotherTmpl: function() {
    Template.firstTmpl.state.get('someName');
  }
});

【问题讨论】:

    标签: javascript node.js meteor


    【解决方案1】:

    您也可以在父模板上设置ReactiveDict,即collectingTmpl

    // always initialize your template instance properties
    // in an onCreated lifecycle event
    Template.collectingTmpl.onCreated(function(){
      this.firstTmplState = new ReactiveDict();
    });
    

    然后您可以使用以下代码在子模板中获取对此模板实例属性的引用:

    Template.firstTmpl.onCreated(function(){
      // warning, this line is depending on how many parent templates
      // the current template has before reaching collectingTmpl
      var collectingTmplInstance = this.view.parentView.templateInstance();
      this.firstTmplState = collectingTmplInstance.firstTmplState;
    });
    
    Template.secondTmpl.onCreated(function(){
      var collectingTmplInstance = this.view.parentView.templateInstance();
      this.firstTmplState = collectingTmplInstance.firstTmplState;
    });
    

    然后,您可以在 3 个模板中的任何一个中使用标准 Template.instance().firstTmplState 语法,它们将始终指向同一个 ReactiveVar 实例,该实例定义为 collectingTmpl 的属性。

    【讨论】:

      【解决方案2】:

      如果您处理当前的 blaze 问题(缺少数据上下文),您可以通过 Template.parentData() 访问其他模板变量。

      查看这个 MeteorPad 作为演示,按下按钮时每个玩家的背景颜色都会改变。颜色由它们的父模板定义:

      http://meteorpad.com/pad/zoiAvwuT3XXE5ruCf/Leaderboard_Template_parentData_Bug

      您也可以在 GitHub PullRequest 上阅读我建议的一些更新

      https://github.com/meteor/meteor/pull/4797

      干杯 汤姆

      【讨论】:

        猜你喜欢
        • 2016-04-02
        • 2016-02-21
        • 1970-01-01
        • 2015-03-28
        • 2016-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多