2014-04-29 166 views
6

我有一個模板,其中DOM已更改,並且我希望在保存到數據庫時重新渲染模板。在Blaze之前,如果模板中某處存在反應變量,流星會重新渲染整個模板,但現在我怎麼能做到這一點?流星:強制使用Blaze收集更新後重新渲染整個模板

我有剪輯在鐵路由器的路由設置的集合:

ClipsController = RouteController.extend({ 
    data: function() { 
     clips = Clips.find({}, {sort: {created: 1}}); 
     return {clips: clips}; 
    } 
}); 

和模板爲剪輯

<template name="clips"> 
    {{#each clips}} 
    {{> clip}} 
    {{/each}} 
</template> 

然後,我有模板clip

<template name="clip"> 
    <article class="clip" id="{{_id}}"> 
    {{{content}}} 
    <ul class="tags"> 
     {{#each tags}} 
     <li><a href="/#{{this}}">#{{this}}</a></li> 
     {{/each}} 
    </ul> 
    </article> 
</template> 

而對於這個模板,改變了DOM,然後腳本保存

Template.clip.events({ 
    'click .edit': function(event, template) { 
    template.$('.tags li').each(function() { 
     $(this).text($(this).text().replace(/^#(.*)/, "$1")); 
    }); 
    }, 

    'click .save': function(event, template) { 
    var data = { 
     //... 
    }; 

    Clips.update({_id: this._id}, data); 

    // How to rerender the template ? 
    } 
}); 

回答

10

我不相信火焰提供任何方式重新呈現整個模板火焰的一點是要有細粒度更新。

實現此目的的一種快速和骯髒的方法可能是使用Session,一個模板幫助器和一個封裝整個模板的{{#unless}}塊,然後在更新之前將Session鍵設置爲true,並設置false在導致{{#unless}}塊中的所有內容重新渲染之後。

Template.clips.noRender = function(){ 
    return Session.get("noRender"); 
} 

Template.clip.events({ 
    'click .edit': function(event, template) { 
    template.$('.tags li').each(function() { 
     $(this).text($(this).text().replace(/^#(.*)/, "$1")); 
    }); 
    }, 

    'click .save': function(event, template) { 
    var data = { 
     //... 
    }; 

    Session.set("noRender", true); 

    Clips.update({_id: this._id}, data, function(){ 
     Session.set("noRender", false); 
    }); 

    // How to rerender the template ? 
    } 
}); 

<template name="clips"> 
    {{#unless noRender}} 
    {{#each clips}} 
     {{> clip}} 
    {{/each}} 
    {{/unless}} 
</template> 
+0

這很聰明!在我自己的情況下,使用略微不同的模板進行編輯/查看並動態切換模板的確有竅門,但這是一個很好的竅門。 – Jide

+0

聰明,可怕,但非常有用。 :) –

0

鐵路由器的數據動作是被動違約。

clips = Clips.find({}, {sort: {created: 1}}); 

更換到

clips = Clips.find({}, {sort: {created: 1}}).fetch(); 
+0

似乎都工作一樣,還是我失去了一些東西? – Jide

+0

第一個返回一個遊標(這是一個Meteor對象),另一個給出一個包含結果的數組。 –

+0

我意識到這一點,但爲什麼我會返回一個數組而不是遊標? – Jide

0

我認爲更好的方法是使用Tracker.afterFlush

例如:

Tracker.autorun -> 
    Tracker.afterFlush -> 
     # DOM is updated, why don't you do something here? 
2

我覺得這可能是一個更好的解決方案也流星方式。

../clips.js 

Template.clips.onRendered(function(){ 

    this.autorun(function(){ 
    Template.currentData(); 
    }); 

}); 

template.autorun(runFunc)

可以使用this.autorun從onCreated或onRendered回調 被動更新DOM或模板實例。您可以在此回調中使用 Template.currentData()來訪問模板實例的反應數據 上下文。

http://docs.meteor.com/#/full/template_autorun

相關問題