[英]Meteor - Passing data between helpers, events and templates
我不確定如何處理我的問題。 我是否應該將我的事件中的變量設置為我的模板中的空格鍵語法字段,或者以某種方式將我返回的事件數據傳遞給我的助手。 一切都已正確發布和訂閱。
問題:我正在嘗試創建它,以便用戶可以單擊目錄列表(DirectoryList集合)中任何人旁邊的“添加”按鈕,並將該用戶信息添加到“聯系人列表”集合中。 它只是一個消息傳遞應用程序,人們可以滾動每個人的目錄,並將用戶添加到他們的聯系人列表。 這是我的文件:
templates> directoryList.html
<template name="directoryList">
{{> searchDirectory}}
<ul>
{{#each directoryList}}
<li>
{{firstname}} {{lastname}} <button name="addFriend" id="addFriend">Add</button>
</li>
{{/each}}
</ul>
</template>
助手> directoryList.js
Template.directoryList.helpers({
'directoryList': function(){
return DirectoryList.find({}, {sort: {createdAt: -1}});
}
});
事件> directoryList.js
Template.directoryList.events({
'click .addFriend': function(event){
event.preventDefault();
var currentUserId = Meteor.userId();
var currentContact = DirectoryList.findOne(this._id);
var currentContactFirstname = currentContact.firstname;
var currentContactLastname = currentContact.lastname;
var currentContactEmail = currentContact.email;
console.log("test");
ContactsList.insert({
firstname: currentContactFirstname,
lastname: currentContactLastname,
email: currentContactEmail,
createdBy: currentUserId
});
}
});
它顯然在我的事件中給我{{}}語法錯誤,但我不知道還能做什么或如何讓它工作。 以為它可能能夠從模板繼承那些字段,但我猜不是嗎?
在您的事件處理程序中, this
已包含當前聯系人,您無需再次查找。 您可以將事件處理程序簡化為:
Template.directoryList.events({
'click .addFriend': function(event){
event.preventDefault();
console.log(this);
ContactsList.insert({
firstname: this.firstname,
lastname: this.lastname,
email: this.mail,
createdBy: Meteor.userId()
});
}
});
您的事件處理程序適用於addButton
類,其中您的按鈕沒有addButton
類。 您需要在模板中將id更改為class。
<template name="directoryList">
{{> searchDirectory}}
<ul>
{{#each directoryList}}
<li>
{{firstname}} {{lastname}} <button name="addFriend" class="addFriend">Add</button> <!-- CHANGED ID TO CLASS FOR THIS BUTTON -->
</li>
{{/each}}
</ul>
</template>
您可以按照其他答案避免不必要的查詢來提高性能。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.