编辑:
给出下面的答案,使用 Meteor Deps似乎是理想的选择,因为我想在两个不同的模板之间共享数据,并且它应该对发生的任何更改使用react。
澄清一下:我的数据来源是 Template.reactiveTable
目的地是Template.buttons
。当数据在reactiveTable
时更改,我希望按钮能够反射(reflect)这一点。
结束编辑
我希望设置 buttons
的值基于表的内容(具体来说,<h1>
值)。
按钮.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 addreactive-dict
当创建buttons
模板时,它会初始化其自己的内部 react 状态。呈现后,它会使用页面上所有 h1
标记中的文本填充该状态。由于该状态是 react 性的,因此它将导致 testButtons
运行并将格式正确的数据返回到您的模板。请参阅我的帖子Scoped Reactivity了解更多详情。
由于 buttons
模板使用范围 react 性,因此可以在任何页面上多次使用它,而无需修改父模板。
关于javascript - 设置Meteor JS Helper的返回值,动态注入(inject)到模板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25550593/