繁体   English   中英

将参数传递到骨干视图的Backbone事件对象

[英]Passing parameters into the Backbone events object of a backbone view

我有一个Backbone View的以下事件。 它是一个产品视图 - 有三个标签(“All”,“Top 3”,“Top 5”)

我可以以某种方式将参数传递给方法声明,以便它等效于以下(这不起作用)?

events : {
    "click #top-all":          "topProducts(1)"
    "click #top-three":      "topProducts(2)"
    "click #top-ten":         "topProducts(3)"
},
topProducts(obj){
    // Do stuff based on obj value
}

您可以将额外参数放在可点击项目的数据属性中; 这样的事情:

<a id="top-all" data-pancakes="1">

然后topProducts可以自己解决:

topProducts: function(ev) {
    var pancakes = $(ev.currentTarget).data('pancakes');
    // And continue on as though we were called as topProducts(pancakes)
    // ...
}

我通常喜欢做这样的事情:

events : {
   "click #top-all":    function(){this.topProducts(1);}
   "click #top-three":  function(){this.topProducts(2);}
   "click #top-ten":    function(){this.topProducts(3);}
},
topProducts(obj){
   // Do stuff based on obj value
}

你可以做的,只是检查在参数中作为currentTarget接收的元素的id。

topProduct: function (e) {
    var id = e.currentTarget.id;
    if (id == "top-all") // Do something
    else if (id == "top-5") // Do something
    else if (id == "top-3") // Do something
}

你可以使用闭包来做到这一点:

EventObject.on(event, (function(){
    var arg = data; // Closure preserves this data
    return function(){
        doThis(arg);
    }   
})());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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