?
我正在使用流星和我的项目大火,我想在流星模板中调用JavaScript函数。更确切地说,我当然使用发布者订阅者,但是当我订阅以从mongo DB中检索信息时,我想要触发一个函数。?
事实上,我检索数据,但它处理像“真”或“假”的行数据,我想根据数据结果调用影响不同属性的函数。例如,如果my db的元素设置为“true”,那么订阅将准备就绪(或者一旦我的页面加载完成),它将用绿色矩形替换“true”。
要做到这一点,我想知道,如果我们可以用
Template.devicesConfiguration.onCreated(function(){
var self = this;
self.autorun(function(){
self.subscribe('Buttons');
//call a javascript function that uses the result of the db
});
});
或
Template.devicesConfiguration.helpers({
buttons:()=>{
//call a javascript function that uses the result of the db
return ButtonsCollection.find({});
}
});
,甚至是方法?
有人有想法吗?非常感谢 !
我会去与一个订阅,然后简单的辅助功能:
Template.devicesConfiguration.onCreated(function() {
Meteor.subscribe('Buttons'); // Subscribe to your buttons
});
Template.devicesConfiguration.helpers({
// Will return a "transformed" array of all the Buttons in collection
buttons(){
return ButtonsCollection.find({}) // Find all buttons
.map(button => {
// Do something with button object
// Like check true/false and change rectangle color
})
}
});
我只是订阅模板创建的数据。
然后,我注册了一个buttons
帮助程序,它从集合中返回数据,但在返回数据之前对数据执行转换(map函数)。
然后,您可以在模板中使用{{#each button in buttons}}
来遍历数据并显示每个按钮。
Template.devicesConfiguration.helpers({
buttons() {
return ButtonsCollection.find({}).map(button => {
if(button.value === true) button.className = 'green';
else button.className = 'red';
})
}
});
类似:
{{#each button in buttons}}
<button class={button.className}>{button.name}</button>
{{/each}}
没有写任何火焰在一段时间,但我希望你的想法。
感谢您的回答,我理解这个想法:)我试图实现它。它的作品,但手柄不显示我的按钮的属性,我用{{button name}},{{button.name}},{{name}},{{button name}},'' {button.name}'或者'{name}'。然而,助手部分的作品,我可以例如'console.log(button.name + button。值)'根据它在if循环中的值语句。 –
我试图这样做,但错误,我猜语法不正确,但我理解这个想法。 这里模板助手的代码: '按钮:)(=> {\t 返回ButtonsCollection.find({})映射(按钮=> { 变种buttonValue = ButtonsCollection.find({},{字段:{值: “真”}})取(); 变种CheckButtonsLed = document.getElementsByClassName( “CheckButtonsLed”); 为(I = 0;我