如何删除/销毁附加到主体的主干视图

How to remove/destroy Backbone View which is appended to body

本文关键字:主体 视图 何删除 删除      更新时间:2023-09-26

我有这个主干应用程序,点击事件会触发一个新的视图,并将其作为弹出窗口附加到DOM的主体。不过,我的问题是,当我在视图外部单击时,我希望新视图被完全删除。以下是触发新视图的事件:

view1.js:

events: {
    'click .btn': 'popupView'
},
popupView: function(){
  new popup.View().render();
}

然后代码到我的"弹出"视图:

popup.View = Backbone.View.extend({
    template: 'some_template',  
    initialize: function(){
        this.$el.appendTo("body");
        this.render();
    },
    afterRender: function(){
        $("body").click(function(){
            $('div.wrap').remove(); // removes the wrap div from the html template
            this.remove() // does not work
    })
})

问题是,在弹出视图被渲染后,我一点击主体,它就会从DOM中删除包装div html,但当我再次打开弹出视图时,前一个html会被渲染两次等等。因此,这表明视图毕竟没有被删除/销毁。

有什么建议可以解决这个问题吗?谢谢

这是因为回调函数内部的this上下文不同。试试看:

afterRender: function(){
    var that = this;
    $("body").click(function(){
        $('div.wrap').remove();
        that.remove(); // should work
})

让我知道这是否有效