我有一个Backbone View的以下事件。它是一个产品视图 - 有三个标签(“全部”,“前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
}
答案 0 :(得分:80)
您可以将额外参数放在可点击项目的数据属性中;像这样的东西:
<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)
// ...
}
答案 1 :(得分:38)
我通常喜欢这样做:
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
}
答案 2 :(得分:9)
你可以做的,只是检查在参数中作为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
}
答案 3 :(得分:3)
你可以使用闭包来实现:
EventObject.on(event, (function(){
var arg = data; // Closure preserves this data
return function(){
doThis(arg);
}
})());