【问题标题】:Access a Template's Instance scope and inject data访问模板的实例范围并注入数据
【发布时间】:2016-02-09 03:38:10
【问题描述】:

我正在寻找一种方法来访问并将一些数据注入到模板的变量中。我想在路由之前获取数据,并在需要的模板呈现时使其可用。

直接访问该范围会很有用。这是我的特定模板的代码(尚未渲染),变量是 allFriends

Template.FacebookLook.onRendered(function () {
  const instance = Template.instance();

  if(!!Friends.find().fetch()) {
    instance.allFriends = Friends.find().fetch();
  } else {
    Popup.show("Invite your friends", null);
  }

});

我在论坛上发现了一些讨论,我得到了:

Template.InitView.onCreated(function () {
  Blaze.getView('FacebookLook').allFriends.set([]);
});

但我收到了Uncaught Error: There is no current view

【问题讨论】:

    标签: javascript meteor meteor-blaze


    【解决方案1】:

    您想在FacebookLook 视图中插入数据吗?不需要Blaze.getView().

    您可以使用ReactiveVar 将其存档。

    Template.FacebookLook.onRendered(function () {
      var tmpl = this;
    
      if(!!Friends.find().fetch()) {
        instance.allFriends = Friends.find().fetch();
      } else {
        Popup.show("Invite your friends", null);
      }
      tmpl.allFriends.set([]);
    });
    
    Template.FacebookLook.onRendered(function () {
      var tmpl = this;
      tmpl.allFriends = new ReactiveVar;
    });
    

    然后,您可以访问帮助程序或事件中的数据,例如

    Template.FacebookLook.helpers({
      test:function(){
       return Template.instance().allFriends.get()
      }
    });
    

    #编辑 1

    根据你的问题,你需要做的是这个。

    Template.InitView.onCreated(function () {
      var facebookTmpl = Blaze.getView('FacebookLook') && Blaze.getView('FacebookLook').templateInstance();
      facebookTmpl.allFriends.set([]);
    });
    

    请注意,您需要知道这只有在 InitView 视图是 FacebookLook 视图中的包装器时才有效,我正在谈论这个。

    <template name="FacebookLookTemplate">
       {{> InitView}} {{! here initView can access the parent or wrapping template}}
    </template>
    

    【讨论】:

    • 我正在寻找的更多的是一个电话和另一个范围的联系。我用onCreated 部分更新了我的问题,以使其更清晰
    • 谢谢,我的两个模板完全不同,所以没有父子关系。我会暂时投票,因为它可能会解决我的问题
    猜你喜欢
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2021-09-02
    • 2012-01-03
    • 2019-01-04
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多