pap*_*del 52 javascript backbone.js
我有一个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
}
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 80
您可以将额外参数放在可点击项目的数据属性中; 这样的事情:
<a id="top-all" data-pancakes="1">
Run Code Online (Sandbox Code Playgroud)
然后topProducts可以弄明白:
topProducts: function(ev) {
var pancakes = $(ev.currentTarget).data('pancakes');
// And continue on as though we were called as topProducts(pancakes)
// ...
}
Run Code Online (Sandbox Code Playgroud)
Dre*_*Dre 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
}
Run Code Online (Sandbox Code Playgroud)
你可以做的,只是检查在参数中作为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
}
Run Code Online (Sandbox Code Playgroud)