Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更改el属性时未触发主干视图事件_Javascript_Backbone.js - Fatal编程技术网

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
的正确方法是使用:

setElement
view.setElement(element)

如果要将主干视图应用于不同的DOM元素,请使用setElement,它还将创建缓存的
$el
引用,并将视图的委派事件从旧元素移动到新元素

所以你应该可以这样做:

this.setElement($(template).replaceAll(this.el));