Javascript 更改el属性时未触发主干视图事件
我对主干网还不熟悉,并尝试做一些例子,但我一直坚持这一点。 我的观点如下:Javascript 更改el属性时未触发主干视图事件,javascript,backbone.js,Javascript,Backbone.js,我对主干网还不熟悉,并尝试做一些例子,但我一直坚持这一点。 我的观点如下: CommentBoxView = Backbone.View.extend({ initialize: function () { this.render(); }, render: function () { var template = _.template( $("#comment_box_template").html(), {} ); th
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);
}
});
一切正常,但如果我更换
html(模板)
为此:
this.el=$(模板).replaceAll(this.el)
根本不会触发按键事件。
有人能解释一下为什么会发生这种情况,以及如何让这段代码工作吗?非常感谢大家。主干使用视图的方法将jQuery调用绑定到视图的,这个委托处理所有视图的事件。如果您这样做:
this.el = $(template).replaceAll(this.el);
您将丢失绑定到this.el的委托
,您的事件也随之丢失。你也会以不匹配的this.el而告终,这也不好。更改视图的el
的正确方法是使用:
setElementview.setElement(element)
如果要将主干视图应用于不同的DOM元素,请使用setElement,它还将创建缓存的$el
引用,并将视图的委派事件从旧元素移动到新元素
所以你应该可以这样做:
this.setElement($(template).replaceAll(this.el));