2014-10-09 102 views
9

我不得不將渲染回調分配給我的所有模板。渲染流星火焰中所有模板的回調

直到0.9.0我用來做這樣的:

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

但現在,模板是一個構造函數,而不是一個對象,所以這種方法不會在這裏工作。當使用Blaze渲染所有模板時,是否有任何方法將回調函數傳遞給所有模板或引導函數?

回答

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

這實際上是我需要的,但任何想法在哪裏把這個代碼,以便加載後所有的模板已被定義?而不是檢查'Template [property] .viewName',可以使用Blaze.isTemplate函數 – 2014-10-09 15:02:51

+1

感謝Blaze.isTemplate'建議,我更新了我的代碼以使用客戶端'Meteor.startup'來確保它是每個模板定義後執行。 – saimeunt 2014-10-09 15:07:27

+0

工程就像一個魅力!十分感謝! – 2014-10-09 15:12:05

-4

隨着Meteor 1.2.1的模板對象具有onRendered(鉤子)函數來完成一個'所有模板'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(回調)的推遲的更新是可選的,以你的應用需求。

+2

我在流星1.2.1上,但是這個解決方案不起作用: 'TypeError:Template.onRendered不是一個函數' – 2016-02-10 14:23:28

+0

不知道爲什麼這對你沒有效果,顯然是其他人對你投票的答案,但是這個功能在我的幾個生產應用中按預期工作。查看[源代碼](https://github.com/meteor/blaze/commit/1d175814f1d9ad857743601f55073395dbdfedad),如果可能的話確認你的Template對象實際上是一個Meteor Blaze模板對象,並且不會被替換/變異... – user1756588 2016-10-05 15:10:05

+0

剛剛檢查過流星1.4和'Template.onRendered'是'undefined'。 – 2017-05-03 09:27:30