繁体   English   中英

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

[英]Meteor - Passing data between helpers, events and templates

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

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

助手> 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}} &nbsp; <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM