我在理解 Backbone subview 中的事件绑定(bind)时遇到问题。我的观点定义如下:
TenantView = Backbone.View.extend({
events: {
"click": "setActive"
},
initialize: function() {
this.parentEl = this.options.parentEl;
return this.render();
},
template: new EJS({
url: '/scripts/templates/tenant.ejs'
}),
render: function() {
$(this.parentEl).children('ul').append(this.template.render(this.model));
return this;
},
setActive: function(event) {
return this.model.set('active', true);
}
});
该模板仅包含 li
包含 a
。这样做,我的 View 上的点击事件没有被捕获,我的方法setActive
永远不会被触发。
当我将视野扩展为el
时属性如 el: 'li'
我的 (2) View 之一正常运行并触发 setActive
功能。第二个 View 根本没有反应。如果我检查 el
View 初始化期间的属性,工作 View 的 el
属性指向右侧li
,失败的 View el
指向第一个li
可以在页面中找到。
正如大家所见,当谈到 el
的含义时,我完全迷失了方向。属性。
问题是,如何将 View 上的点击绑定(bind)到这个 View setActive
功能?
谁能帮我解答一下吗?
问候 菲利克斯
最佳答案
首先,您可以阅读documentation和 this 。那里给出了关于el
的解释。
由于 TenantView
具有 parentEl
属性,我假设它是从某个 parent_view
渲染的。我建议采用如下所示的方法并尝试一下。
var ChildView = Backbone.View.extend({
tagName : "li", // change it according to your needs
events : {
"click": "setActive"
},
initialize : function() {
_.bindAll(this, "setActive");
// code to initialize child_view
},
render : function() {
// as I'm not familiar with the way you are using template,
// I've put simple call to render template, but it should render the
// content to be kept inside "li" tag
this.$el.html(this.template());
return this;
},
setActive : function(event) {
// code to be executed in event callback
}
});
var ParentView = Backbone.View.extend({
el : "#parent_view_el",
initialize : function() {
// parent view initialization code
},
render : function() {
// a place from where ChildView is initialized
// might be a loop through collection to initialize more than one child views
// passing individual model to the view
var child_view = new ChildView();
this.$("ul").append(child_view.render().$el); // equivalent to this.$el.find("ul")
return this;
}
});
希望对你有帮助!!
关于javascript - 如何在 Backbone subview 中绑定(bind)点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13269071/