删除backbone.js视图不允许我添加另一个视图

Removing backbone.js view does not allow me to add another view

本文关键字:视图 添加 另一个 允许我 不允许 js 删除 backbone      更新时间:2023-09-26

似乎每当我调用view。remove()时它不仅从dom中删除了视图还删除了整个body

我在每个视图创建后调用showView

showView : function(view) {
        if (this.currentView) {
            this.currentView.remove();
            this.currentView.unbind();
            if (this.currentView.onClose) {
                this.currentView.onClose();
            }
        }
        this.currentView = view;
        $('body').html(this.currentView.render().el);
  }

既然不再有body元素,我就不能再添加一个视图

Chrome调试器输出

$('html')
<html>​
<script id=​"tinyhippos-injected">​…​</script>​
<head>​…​</head>​
</html>​

一旦view.remove()运行,屏幕变白,不再重新填充$('body').html(this.currentView.render().el);

编辑:

我将每个视图从el: $('.body')改为el: '。mainContent',并在index.html文件中添加了一个。

在app.showView中添加mainContentdiv,如果它已被删除。最好删除一个div而不是整个body。

if($('.mainContent').length == 0)
    $('body').append('<div class="mainContent"></div>');

解决方案:

我需要重写viewremove方法。我不想删除整个视图,只删除内容:在主干js

中重新创建被删除的视图
Backbone.View.prototype.remove = function() {
    this.undelegateEvents();
    this.$el.empty();
    return this;
    };

由于您通过$('body').html(this.currentView.render().el);添加视图,因此不需要在视图中设置el属性。

当你在视图中设置el属性时,你是在告诉backbone查找该元素并将其用作基元素。这样做时,您不需要将其添加到$('body').html()页面,您可以调用view.render()。但是当你调用remove()时,它会移除你设置的el(在你的例子中是'body'或'. maincontent ')。

如果你没有指定el,它会为你生成一个新元素。在这种情况下,您确实需要使用$('body').html(this.currentView.render().el);添加到页面,但是当您调用remove()时,它只会删除生成的元素。

因此,如果您只是从视图中删除el: '.mainContent',您可以避免检查并重新添加该元素。你也不需要重写remove.

从视图中删除el: '.mainContent'后,您可以简单地这样做:

$('body').html(view1.render().el);
view1.remove();
$('body').html(view2.render().el);