Javascript 将参数传递给主干视图的主干事件对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7823556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing parameters into the Backbone events object of a backbone view
提问by papdel
I have the following events for a Backbone View. Its a product view - with three tabs ("All", "Top 3", "Top 5")
我有以下主干视图事件。它是一个产品视图 - 带有三个选项卡(“全部”、“前 3 名”、“前 5 名”)
Can I somehow pass a parameter into the method declaration so that it is equivalent to the following (this doesn't work)?
我能否以某种方式将参数传递到方法声明中,使其等效于以下内容(这不起作用)?
events : {
"click #top-all": "topProducts(1)"
"click #top-three": "topProducts(2)"
"click #top-ten": "topProducts(3)"
},
topProducts(obj){
// Do stuff based on obj value
}
回答by mu is too short
You could put the extra argument in a data attribute on the clickable item instead; something like this:
您可以将额外的参数放在可点击项目的数据属性中;像这样:
<a id="top-all" data-pancakes="1">
And then topProducts
can figure it out itself:
然后topProducts
可以自己弄清楚:
topProducts: function(ev) {
var pancakes = $(ev.currentTarget).data('pancakes');
// And continue on as though we were called as topProducts(pancakes)
// ...
}
回答by Dre
I generally prefer to do something like this:
我通常更喜欢做这样的事情:
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
}
回答by sachinjain024
What you can do, is just check the id of the element which is received as currentTarget in arguments.
您可以做的只是检查在参数中作为 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
}
回答by Yusuf Bhabhrawala
You can do so using closures:
你可以使用闭包来做到这一点:
EventObject.on(event, (function(){
var arg = data; // Closure preserves this data
return function(){
doThis(arg);
}
})());