将parameter passing到主干视图的Backbone事件对象
我有以下事件的骨干视图。 它的产品视图 – 三个选项卡(“全部”,“前3名”,“前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
它本身:
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); } })());