2016-04-29 92 views
1

我不知道如何處理我的問題。是否應該將我的事件中的變量設置爲我的模板中的spacebars語法字段,或將我返回的事件數據以某種方式傳遞給我的助手。一切都已正確發佈和訂閱。流星 - 助手,事件和模板之間傳遞數據

問題:我試圖讓用戶可以單擊目錄列表(DirectoryList集合)中任何人員旁邊的「添加」按鈕,並將該用戶信息添加到聯繫人列表集合中。它只是一個消息應用程序,用戶可以滾動每個人的目錄並將用戶添加到他們的聯繫人列表中。下面是我的文件:

模板> directoryList.html

<template name="directoryList"> 
    {{> searchDirectory}} 
    <ul> 
     {{#each directoryList}} 
      <li> 
       {{firstname}} {{lastname}} &nbsp; <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 
     }); 
    } 
}); 

其明顯扔我一個錯誤的{{}}語法在我的事件,但我不知道還有什麼要做或如何讓這個工作。認爲它可能能夠從模板繼承這些領域,但我猜不是?

+0

問題更容易回答,當你指出問題的正確性。哪一行發生錯誤,以及打印到控制檯的內容是什麼?另外,'currentContact'是否正確提取? –

+0

我很抱歉。它沒有在控制檯或命令提示符中顯示任何錯誤,基本上只是一個簡單的按鈕被點擊而什麼也不做。 並沒有任何內容正在打印到控制檯。我將console.log(「test」)作爲測試打印出來,但沒有打印出來。 至於currentContact我_assumed_它是。我有一個名爲DirectoryList的集合,發佈並訂閱 –

回答

0

您的事件處理程序是addButton類,在這裏按鈕沒有addButton類。您需要將id更改爲模板中的類。

<template name="directoryList"> 
    {{> searchDirectory}} 
    <ul> 
     {{#each directoryList}} 
      <li> 
       {{firstname}} {{lastname}} &nbsp; <button name="addFriend" class="addFriend">Add</button> <!-- CHANGED ID TO CLASS FOR THIS BUTTON --> 
      </li> 
     {{/each}} 
    </ul> 
</template> 

而且您可以按照其他答案來避免不必要的查詢以提高性能。

希望它有幫助。

+1

你是最棒的!這樣一個簡單的錯誤,它修復了一切。被困在這個好幾天了。謝謝謝謝 –

0

在您的事件處理程序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() 
     }); 
    } 
}); 
相關問題