在视图被替换后,主干视图事件未激发,然后放回页面上

Backbone View events not firing after the view is replaced, then put back on the page

本文关键字:视图 然后 事件 替换      更新时间:2024-02-26

问题:

使用$element.html(anotherView)将视图替换为其他内容,然后使用#element.html(theView)将视图放回页面后,在视图内部设置的事件不会触发。

示例:

var BuggyView = Backbone.View.extend({
    // Event works the at first, but not after the view is replaced, then added back
    //     onto the page
    events:{
        'click #some-element': 'on_click_some_element'
    },
    // This function gets called before the view is replaced by another view, but
    //     not after it is added back into the page the second time
    on_click_some_element:function(event){
        alert('User clicked "some element"');
    }
});

此代码执行后事件工作:

// Create the new view:
var buggyView = new BuggyView({});
// Add the view to the page
$element.html(buggyView.el);

稍后,当页面上的视图被替换为其他内容时,就会出现此代码:

$element.html(anotherView.el);

将视图添加回页面后,事件不再工作:

$element.html(buggyView.el);

很可能在删除视图时,也删除了视图的绑定事件,您可能需要重新合并事件。或者不使用(jquery).remove-use.declact.

在DOM中设置视图元素后运行render:

$element.html(anotherView.el);
anotherView.render();
$element.html(theView.el);
theView.render();

您的问题可能是渲染没有再次运行。您只是在切换DOM分配。