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

时间:2016-04-29 02:37:46

标签: javascript templates events meteor helpers

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

问题:我正在尝试创建它,以便用户可以单击目录列表(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>

助手&GT; directoryList.js

Template.directoryList.helpers({

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

});

事件&GT; 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
        });
    }
});

它显然在我的事件中给我{{}}语法错误,但我不知道还能做什么或如何让它工作。以为它可能能够从模板继承这些字段,但我猜不是吗?

2 个答案:

答案 0 :(得分: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()
        });
    }
});

答案 1 :(得分:0)

您的事件处理程序适用于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>

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

希望它有所帮助。

相关问题