如何传递函数以使用Blaze捕获Meteor中自定义组件中的事件

Sha*_*ara 3 meteor meteor-blaze

我想知道如何绑定/设置模板传递参数值以点击Meteor中模板中项目的事件.

我正在使用Meteor 0.7.0.1和Blaze UI包.我的主要想法是使用Blaze模板引擎在Meteor中构建可重用的自定义组件.我有以下组件,目前工作正常但我希望这可以更自定义并删除一些依赖项.这是我的组件模板postLinks

<template name="postLinks">
    <div id="link-popover-wrapper" >
        <ul class="link-popover">
        {{#each linkOptions}}
            <li><a tabindex="-1" class="link-action" id="link-{{value}}" href="#">{{label}}</a>
            </li>
         {{/each}}
        </ul>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)

postLinks组件用于myPostItem帮助程序.

Template.myPostItem.events({

    'click .post-item-link-picker': function (evt, tmpl) {
        var tmpPostId = this._id;
        var tempData = {linkOptions:[{label:'Favorite', value : 'favorite'},{label:'Wish list', value : 'wishlist'},{label:'Later', value : 'later'}, {label:"Read", value:"read"}]};

        var linkContent = Template.postLinks(tempData);
        $(".item-link-picker").popover({
            content: linkContent, html: true, placement: 'bottom', trigger: "manual",
            template: "UI_POPOVER_TEMPLATE"});
            $("#item-link-picker-"+tmpPostId).popover('show');
    },

    'click .link-action': function (evt, tmpl) {
        //.... some code here to update link selection in db
    }
});
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,我想改进它以便跟随

  • 从外部传递项目单击事件以绑定到link-actionlike

经过以上两次更改后,它将如下所示:

Template.myPostItem.events({

    'click .post-item-link-picker': function (evt, tmpl) {
        var tmpPostId = this._id;
        var tempData = { itemClick:function(){}, linkOptions:[{label:'Favorite', value : 'favorite'},...]};
        var linkContent = Template.postLinks(tempData);
        $(".item-link-picker").popover({
            content: linkContent, html: true, placement: 'bottom', trigger: "manual",
            template: "UI_POPOVER_TEMPLATE"});
        $("#item-link-picker-"+tmpPostId).popover('show');
    }
});
Run Code Online (Sandbox Code Playgroud)

我缺乏知道如何/在何处将传递的事件处理函数绑定到link-action模板或帮助器中的元素.如果有人能帮忙找到办法,我真的很感激.

Tom*_*cik 6

你反过来使用jQuery事件触发系统,所以

Template.myPostItem.events({
  'click .link-action': function (evt, tmpl) {
     $(evn.target).trigger('post-link-action', this /* extra data */);
  },
});
Run Code Online (Sandbox Code Playgroud)

可以在任何父模板中轻松捕获此事件:

<template name="someOtherTamplate">
  {{> myPostItem}}
</template>


Template.someOtherTemplate.events({
  'post-link-action': function (evt, tmpl, extra) {
     // the user of your component can define their custom behavior here
   },
});
Run Code Online (Sandbox Code Playgroud)

请注意,事件extra参数仅在下一个Meteor版本中受支持.目前(0.8.0)它包含在devel分支机构中.