如何将参数传递给视图 [英] How to pass parameters to a view
问题描述
我有一系列按钮,点击后会在按钮下方显示一个弹出菜单。我想将按钮的位置传递给视图。我该怎么做?
I have a series of buttons which when clicked display a popup menu positioned just below the button. I want to pass the position of button to the view. How can I do that?
ItemView = Backbone.View.extend({
tagName: 'li',
events: {
'click': 'showMenu'
},
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
return $(this.el).html(this.model.get('name'));
},
showMenu: function() {
var itemColl = new ItemColl();
new MenuView({collection: itemColl}); // how to pass the position of menu here?
}
});
推荐答案
您只需在构造时传递额外参数MenuView。无需添加初始化
功能。
You just need to pass the extra parameter when you construct the MenuView. No need to add the initialize
function.
new MenuView({
collection: itemColl,
position: this.getPosition()
})
然后,在 MenuView
中,您可以使用 this.options.position
。
And then, in MenuView
, you can use this.options.position
.
更新: @ mu状态太短,自1.1.0起, Backbone Views不再自动附加传递给构造函数的选项作为this.options,但如果您愿意,可以自己动手。
UPDATE: As @mu is too short states, since 1.1.0, Backbone Views no longer automatically attach options passed to the constructor as this.options, but you can do it yourself if you prefer.
所以在你的初始化
方法,您可以将选项
保存为 this.options
:
So in your initialize
method, you can save the options
passed as this.options
:
initialize: function(options) {
this.options = options;
_.bindAll(this, 'render');
},
或使用更精细的方式由@Brave Dave描述。
这篇关于如何将参数传递给视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!