Meteor-在助手、事件和模板之间传递数据

Meteor - Passing data between helpers, events and templates

本文关键字:之间 数据 事件 Meteor-      更新时间:2023-09-26

我不知道如何处理我的问题。我是应该将事件中的变量设置为模板中的空格键语法字段,还是以某种方式将返回的事件数据传递给助手。所有内容都已正确发布和订阅。

问题:我试图让用户可以单击目录列表(DirectoryList集合)中任何人旁边的"添加"按钮,并将用户信息添加到联系人列表集合中。它只是一个消息应用程序,用户可以滚动每个人的目录,并将用户添加到他们的联系人列表中。这是我的文件:

templates>directoryList.html

<template name="directoryList">
    {{> searchDirectory}}
    <ul>
        {{#each directoryList}}
            <li>
                {{firstname}} {{lastname}} &nbsp; <button name="addFriend" id="addFriend">Add</button>
            </li>
        {{/each}}
    </ul>
</template>

helpers>directoryList.js

Template.directoryList.helpers({
    'directoryList': function(){
        return DirectoryList.find({}, {sort: {createdAt: -1}});
    }
});

事件>目录List.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
        });
    }
});

很明显,这给我的事件中的{{}}语法带来了一个错误,但我不知道还能做什么,也不知道如何让它发挥作用。我想它可能能够从模板中继承这些字段,但我想不行?

您的事件处理程序用于addButton类,而您的按钮没有addButton类。您需要在模板中将id更改为class。

<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>

您可以按照其他答案进行操作,以避免不必要的查询,从而提高性能。

希望能有所帮助。

在您的事件处理程序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()
        });
    }
});