[英]Set the return value of Meteor JS Helper, inject this dynamically into template
編輯:
給定以下答案,使用Meteor Deps似乎是理想的游戲,因為我想在兩個不同的模板之間共享數據,並且它應該對發生的任何變化都具有反應性。
需要說明的是:我的數據源是Template.reactiveTable
,目的地是Template.buttons
。 當數據在reactiveTable
的變化,我想按鈕來反映這一點。
結束編輯
我想根據表的內容設置buttons
的值(特別是<h1>
值)。
button.html:
<template name="buttons">
{{#each testButtons }}
<button id="{{ name }}">{{ name }}</button>
{{/each}}
</template>
使用此硬編碼后,它可以按預期工作(兩個按鈕呈現標記為Alice和Bob的按鈕
UI.registerHelper('testButtons', function () {
return [
{ name: "Alice" },
{ name: "Bob" }
]
}
)
模板愉快地接受並呈現此對象數組 。 但是,當我動態生成對象數組時不行。
目標:為我的h1標簽中包含的每個唯一單詞生成一個按鈕(幾乎像博客標簽一樣)。
通過將我的幫助程序代碼替換為下面的代碼段(使用jquery解析<h1>
標簽,生成要發送到模板的數組)。
假設html是:
<h1>foo</h1>
<h1>bar</h1>
<h1>baz</h1>
然后在控制台中運行以下代碼段,將創建uniqStrings = [ "foo", "bar", "baz"];
如預期的。
$( 'h1' ).map(function () {
var words = [];
words.push($(this).text());
uniqStrings = _.uniq(words);
});
然后如何將uniqStrings
發送回我的按鈕模板以呈現n= uniqStrings.length
按鈕? 謝謝!
假設此html:
<body>
<h1>Alice</h1>
<h1>Bob</h1>
{{> buttons}}
</body>
<template name="buttons">
{{#each testButtons }}
<button id="{{ name }}">{{ name }}</button>
{{/each}}
</template>
您可以將其與以下實現一起使用:
Template.buttons.helpers({
testButtons: function() {
var words = UI._templateInstance().state.get('words');
return _.map(words, function(word) {
return {name: word};
});
}
});
Template.buttons.rendered = function() {
var words = $('h1').map(function() {
return $(this).text();
});
this.state.set('words', _.uniq(words));
};
Template.buttons.created = function() {
this.state = new ReactiveDict;
};
注意,您需要執行以下操作: meteor add reactive-dict
創建buttons
模板時,將初始化其自己的內部反應狀態。 呈現后,它將用頁面上所有h1
標簽的文本填充該狀態。 因為該狀態是反應性的,所以它將導致testButtons
運行並將正確格式的數據返回到您的模板。 請參閱我關於范圍反應性的文章以了解更多詳細信息。
由於buttons
模板使用作用域范圍的反應性,因此可以在任意頁面上隨意使用它多次,而無需修改父模板。
雖然我不清楚您為什么要嘗試解析一個表的內容,然后將其呈現到另一個表中(這是您要執行的,不是嗎?),但是基本原理如下:
當模板的任何反應性依賴項發生更改時,模板將重新呈現。 因此,這意味着您需要:
從應用程序結構的角度來看,后者可能不太好,但最容易舉例說明:
var renderDep = new Deps.Dependency(),
words = [];
UI.registerHelper('testButtons', function () {
renderDep.depend();
return words;
});
然后,只要您致電:
$( 'h1' ).map(function () {
words = [];
words.push($(this).text());
uniqStrings = _.uniq(words);
});
確保您致電:
renderDep.changed();
之后,它的所有依賴項(即模板幫助程序)將重新運行並返回新words
內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.