在Meteor Blaze中向所有模板渲染回调函数

9

我需要为所有模板分配渲染回调函数。

在0.9.0之前,我通常是这样做的:

_.each( Template, function( template, name ) {
  //...
  template.rendered = function() {
    //...
  };
});

但是现在模板是一个构造函数而不是一个对象,所以这个方法在这里行不通。有没有办法将回调函数传递给所有模板或在使用Blaze时渲染所有模板后触发函数?
2个回答

9

我想分享一个快速解决方法,遍历每个Template属性以查找是否对应于模板定义,如果是,则指定onRendered回调。

// make sure this code is executed after all your templates have been defined
Meteor.startup(function(){
  for(var property in Template){
    // check if the property is actually a blaze template
    if(Blaze.isTemplate(Template[property])){
      var template=Template[property];
      // assign the template an onRendered callback who simply prints the view name
      template.onRendered(function(){
        console.log(this.view.name);
      });
    }
  }
});

我不知道您的具体用例,因此根据情况可能会有更好的解决方案。

1
这正是我需要的,但你有任何想法在哪里放置这段代码才能在所有模板被定义之后加载它吗?而且,可以使用Blaze.isTemplate函数代替检查 Template[property].viewName - Adam Wolski
1
感谢Blaze.isTemplate的建议,我更新了我的代码,使用客户端的Meteor.startup来确保在每个模板被定义后执行。 - saimeunt
完美运作 - 谢谢,但应该更简单(例如 API 方法)在我看来。 - Rico Leuthold
1
需要将 $.material.init(); 放入所有模板的 fezvrasta:bootstrap-material-design 插件的 onRendered 中。这个方法非常有效!感谢您,加一! - CodeChimp

-4

Meteor 1.2.1 中,Template 对象拥有 onRendered(hook) 函数以实现“所有模板”onRendered行为。

Template.onRendered(function(){
  var template = this;
  Deps.afterFlush(function() {
    console.log("triggering Jquery mobile component creation for "+template.view.name);
    $(template.firstNode.parentElement).trigger("create");
  });
});

通过 Deps.afterFlush(callback) 延迟更新是可选的,取决于您的应用程序需求。


2
我使用的是 Meteor 1.2.1,但这个解决方案不起作用:TypeError: Template.onRendered is not a function - Fabrizio Fortino
不确定为什么这对你和其他投票反对答案的人没有起作用,但是在我的几个生产应用程序中,此功能按预期工作。查看源代码,如果可能,请确认您的Template对象实际上是Meteor Blaze Template对象,而不是被替换/突变... - user1756588
刚刚检查了Meteor 1.4,发现Template.onRendered是未定义的。 - Nicholas Valbusa

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