[英]Making a template helper reactive in Meteor
我正在構建一個聊天應用程序,在我的“新聊天”頁面上,我有一個聯系人列表,您可以通過點擊它們逐個選擇(我在其上應用CSS選擇的類並將用戶ID推送到名為'的數組中newChatters'。
我想讓這個數組可用於幫助器方法,這樣我就可以顯示一個名單的反應列表,以及已添加到聊天中的所有用戶。
我想要顯示反應列表的模板:
<template name="newChatDetails">
<div class="contactHeader">
<h2 class="newChatHeader">{{newChatters}}</h2>
</div>
</template>
只要選擇了聯系人,就會觸發click contactItem事件:
Template.contactsLayout.events({
'click #contactItem': function (e) {
e.preventDefault();
$(e.target).toggleClass('selected');
newChatters.push(this.username);
...
newChatters數組正在正確更新,所以到目前為止一切正常。 現在我需要讓{{newChatters}}被動地更新。 這是我嘗試過的,但它不對,不起作用:
Template.newChatDetails.helpers({
newChatters: function() {
return newChatters;
}
});
我如何以及在何處使用Deps.autorun()來完成這項工作? 我是否甚至需要它,因為我認為輔助方法無論如何都會自動更新失效?
1)在定義對象的同一位置定義Tracker.Dependency
:
var newChatters = [];
var newChattersDep = new Tracker.Dependency();
2)在從對象讀取之前使用depend()
:
Template.newChatDetails.newChatters = function() {
newChattersDep.depend();
return newChatters;
};
3)寫完后使用changed()
:
Template.contactsLayout.events({
'click #contactItem': function(e, t) {
...
newChatters.push(...);
newChattersDep.changed();
},
});
您應該使用Session
對象。
Template.contactsLayout.events({
'click #contactItem': function (e) {
//...
newChatters.push(this.username);
Session.set('newChatters', newChatters);
}
});
接着
Template.newChatDetails.helpers({
newChatters: function() {
return Session.get('newChatters');
}
});
您可以使用本地Meteor.Collection
游標作為反應數據源:
var NewChatters = new Meteor.Collection("null");
模板:
<template name="newChatDetails">
<ul>
{{#each newChatters}}
<li>{{username}}</li>
{{/each}}
</ul>
</template>
事件:
Template.contactsLayout.events({
'click #contactItem': function (e) {
NewChatters.insert({username: this.username});
}
});
幫手:
Template.newChatDetails.helpers({
newChatters: function() { return NewChatters.find(); }
});
為了模擬天生的行為Session
不污染Session
,使用ReactiveVar
:
Template.contactsLayout.created = function() {
this.data.newChatters = new ReactiveVar([]);
}
Template.contactsLayout.events({
'click #contactItem': function (event, template) {
...
template.data.newChatters.set(
template.data.newChatters.get().push(this.username)
);
...
然后,在內部模板中,使用父反應數據源:
Template.newChatDetails.helpers({
newChatters: function() {
return Template.parentData(1).newChatters.get();
}
});
適用於在2015年以上尋找解決方法的人(自2014年起發布)。
我正在實現一個帖子向導pw_module
,我需要根據路由參數自動更新數據:
Router.route('/new-post/:pw_module', function(){
var pwModule = this.params.pw_module;
this.render('post_new', {
data: function(){
switch (true) {
case (pwModule == 'basic-info'):
return {
title: 'Basic info'
};
break;
case (pwModule == 'itinerary'):
return {
title: 'Itinerary'
};
break;
default:
}
}
});
}, {
name: 'post.new'
});
稍后在模板中只需執行以下操作:
<h1>{{title}}</h1>
更新URL的導航如下所示:
<nav>
<a href="{{pathFor route='post.new' pw_module='basic-info'}}">Basic info</a>
<a href="{{pathFor route='post.new' pw_module='itinerary'}}">Itinerary</a>
</nav>
希望它仍然可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.