簡體   English   中英

如何在另一個模板渲染后重新運行/渲染一個流星模板助手?

[英]how to make a meteor template helper re-run/render after another template has rendered?

我在模板Nav中有一個名為{{renderNav}}的模板助手

例如

Template.Nav.renderNav

在該輔助函數中,我想在另一個模板中解析另一個幫助器的渲染輸出

例如助手

Template.contentWindow.content

它提供了html

{{content}}

我的renderNav幫助器想要分割替換{{content}}的html來生成html for

{{renderNav}}

我該怎么做? 現在{{renderNav}}幫助程序執行或運行得更快,因此它無法解析替換{{content}}的html

@Hugo - 我按照你的建議在我的代碼中執行了以下操作

Template.contentWindow.rendered = function() {
    debugger;  
    return Session.set('entryRendered', true);
};

Template.Nav.renderNav = function() {
    debugger;
    var forceDependency;
    return forceDependency = Session.get('entryRendered');
};

當我運行它時,調試器在執行renderNav幫助程序時首先停止。 (這與我在比賽條件方面所看到的有關)。 然后contentWindow呈現並且我點擊Session.set上方的斷點('entryRendered',true)。 但是然后renderNav不再按照你的建議再次運行。 我是否誤解或錯誤地實施了您的建議?

您需要在要重新運行的模板中使用依賴項。 根據您想要獲得的數據,幾乎沒有可能。

例如,您可以在content模板中設置一個反應標記,該標記將通知renderNav它是否已完成繪圖。

Template.contentWidnow.rendered = function() {
    ...

    // Set this on the very end of rendered callback.
    Session.set('contentWindowRenderMark', '' +
        new Date().getTime() +
        Math.floor(Math.random() * 1000000) );
}


Template.renderNav.contentData = function() {
    // You don't have to actually use the mark value,
    // but you need to obtain it so that the dependency
    // is registered for this helper.
    var mark = Session.get('contentWindowRenderMark');

    // Get the data you need and prepare for displaying
    ...
}


根據您提供的更多信息,我們可以創建此類代碼:

content.js

Content = {};
Content._dep = new Deps.Dependency;

contentWindow.js

Template.contentWidnow.rendered = function() {
    Content.headers = this.findAll(':header');
    Content._dep.changed();
}

renderNav.js

Template.renderNav.contentData = function() {
    Content._dep.depend();
    // use Content.headers here
    ...
}

如果你想在contentWindow渲染時自動重建導航,正如Hubert OG建議的那樣,你也可以使用更清晰,更低級的方法來使上下文無效:

var navDep = new Deps.Dependency;

Template.contentWindow.rendered = function() {
    ...
    navDep.changed();
}

Template.renderNav.contentData = function() {
    navDep.depend();

    // Get the data you need and prepare for displaying
    ...
}

有關詳細信息,請參見http://docs.meteor.com/#deps

另一方面,如果要手動渲染另一個模板,可以將其稱為函數:

var html = Template.contentWindow();

返回的html不會被動。 如果您需要反應性,請使用:

var reactiveFragment = Meteor.render(Template.contentWindow);

有關其工作原理的詳細信息,請參閱http://www.eventedmind.com/上關於Spark和反應性的截屏視頻。

UPDATE

要將渲染的片段添加到DOM:

document.body.appendChild(Meteor.render(function () {
    return '<h1>hello</h1><b>hello world</b>';
}));

您還可以使用DOM API直接訪問呈現的節點:

console.log(reactiveFragment.childNodes[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM