我需要为所有模板分配渲染回调函数。
在0.9.0之前,我通常是这样做的:
_.each( Template, function( template, name ) {
//...
template.rendered = function() {
//...
};
});
但是现在模板是一个构造函数而不是一个对象,所以这个方法在这里行不通。有没有办法将回调函数传递给所有模板或在使用Blaze时渲染所有模板后触发函数?
我需要为所有模板分配渲染回调函数。
在0.9.0之前,我通常是这样做的:
_.each( Template, function( template, name ) {
//...
template.rendered = function() {
//...
};
});
我想分享一个快速解决方法,遍历每个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);
});
}
}
});
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) 延迟更新是可选的,取决于您的应用程序需求。
TypeError: Template.onRendered is not a function
。 - Fabrizio FortinoTemplate.onRendered
是未定义的。 - Nicholas Valbusa
Template[property].viewName
。 - Adam WolskiBlaze.isTemplate
的建议,我更新了我的代码,使用客户端的Meteor.startup
来确保在每个模板被定义后执行。 - saimeunt$.material.init();
放入所有模板的fezvrasta:bootstrap-material-design
插件的onRendered
中。这个方法非常有效!感谢您,加一! - CodeChimp