我是 Backbone 的新手,正在尝试做一些示例,但我坚持使用这个。 我有以下 BackBone View :
CommentBoxView = Backbone.View.extend({
initialize: function () {
this.render();
},
render: function () {
var template = _.template( $("#comment_box_template").html(), {} );
this.el.html(template);
},
events: {
"keypress textarea": "doKeyPress"
},
doKeyPress: function (event) {
console.log(event);
}
});
一切正常,但如果我更换
this.el.html(template);
有了这个:
this.el = $(template).replaceAll(this.el);
根本不会触发按键事件。 任何人都可以向我解释为什么会发生以及如何使这段代码有效吗?非常感谢大家。
最佳答案
Backbone 使用 View 的 delegateEvents
绑定(bind) jQuery 的方法 delegate
调用 View 的 el
,这个 delegate
是处理所有 View 事件的。如果你这样做:
this.el = $(template).replaceAll(this.el);
您丢失了绑定(bind)到 this.el
的 delegate
,您的事件也随之消失。你也会得到你的 this.$el
与 this.el
不匹配,这也不好。更改 View 的 el
的正确方法是使用 setElement
:
setElement
view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached
$el
reference and move the view's delegated events from the old element to the new one.
所以你应该可以这样做:
this.setElement($(template).replaceAll(this.el));
关于javascript - 更改 el 属性时主干 View 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229719/