gpt4 book ai didi

javascript - 删除backbone.js View 不允许我添加另一个 View

转载 作者:行者123 更新时间:2023-12-02 19:04:24 26 4
gpt4 key购买 nike

看起来每当我调用 view.remove() 时,它不仅会从 dom 中删除 View ,还会删除整个主体

我在创建每个 View 后调用 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 元素,我无法添加另一个 View

Chrome 调试器输出:

$('html')

<html>​
<script id=​"tinyhippos-injected">​…​</script>​
<head>​…​</head>​
</html>​

一旦 view.remove() 运行,屏幕就会变成白色,并且不会重新填充到 $('body').html(this.currentView.render().el);

编辑:

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

在 app.showView 中,如果 mainContent div 已被删除,我会添加它。删除一个 div 比删除整个 body 更好。

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

解决方案:

我需要重写我的 View 删除方法。我不想删除整个 el,只是删除内容:Recreating a removed view in backbone js

Backbone.View.prototype.remove = function() {
this.undelegateEvents();
this.$el.empty();
return this;
};

最佳答案

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

当您在 View 中设置 el 属性时,您是在告诉 Backbone 找到该元素并将其用作基本元素。这样做时,您不需要将其添加到带有 $('body').html() 的页面中。 ,您只需调用view.render()即可。但是当你调用remove()时,它会删除你设置的el(在你的例子中是“body”或“.mainContent”)。

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

所以,如果你删除 el: '.mainContent'从您的观点来看,您可以避免检查并重新添加该元素。此外,您不必覆盖删除。

删除 el: '.mainContent' 后从 View 上看,你可以简单地这样做:

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

关于javascript - 删除backbone.js View 不允许我添加另一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14464583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com