在Meteor中制作模板助手 [英] Making a template helper reactive in Meteor
问题描述
我正在构建一个聊天应用程序,在我的新聊天页面上,我有一个联系人列表,您可以通过点击它们逐个选择(我在其上应用CSS选择的类并将用户ID推送到数组名为'newChatters'。
I am building a chat application and on my "new chats" page I have a list of contacts, which you can select one by one by tapping them (upon which I apply a CSS selected class and push the user id into an array called 'newChatters'.
我想让这个数组可用于帮助方法,这样我就可以显示一个名单的反应列表,所有用户都被添加到聊天。
I want to make this array available to a helper method so I can display a reactive list of names, with all users who have been added to the chat.
我想要显示被动列表的模板:
The template that I want to display the reactive list in:
<template name="newChatDetails">
<div class="contactHeader">
<h2 class="newChatHeader">{{newChatters}}</h2>
</div>
</template>
只要选择了联系人,就会触发clickItem事件:
The click contactItem event triggered whenever a contact is selected:
Template.contactsLayout.events({
'click #contactItem': function (e) {
e.preventDefault();
$(e.target).toggleClass('selected');
newChatters.push(this.username);
...
newChatters数组正在正确更新所以到目前为止一切都是工作正常。现在我需要让{{newChatters}}被动地更新。这是我尝试过的但它不正确且不起作用:
The newChatters array is getting updated correctly so up to this point all is working fine. Now I need to make {{newChatters}} update reactively. Here's what I've tried but it's not right and isn't working:
Template.newChatDetails.helpers({
newChatters: function() {
return newChatters;
}
});
我如何以及在何处使用Deps.autorun()来完成这项工作?我是否甚至需要它,因为我认为辅助方法无论如何都会自动更新失效?
How and where do I use Deps.autorun() to make this work? Do I even need it, as I thought that helper methods auto update on invalidation anyway?
推荐答案
1)定义 Tracker.Dependency
在您定义对象的同一个地方:
1) Define Tracker.Dependency
in the same place where you define your object:
var newChatters = [];
var newChattersDep = new Tracker.Dependency();
2)在你之前使用 depend()
从对象中读取:
2) Use depend()
before you read from the object:
Template.newChatDetails.newChatters = function() {
newChattersDep.depend();
return newChatters;
};
3)在你之后使用 changed()
写:
3) Use changed()
after you write:
Template.contactsLayout.events({
'click #contactItem': function(e, t) {
...
newChatters.push(...);
newChattersDep.changed();
},
});
这篇关于在Meteor中制作模板助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!