如何防止backbone remove()删除"el"在一个视图中

How do I prevent backbone remove() from removing "el" in a view?

本文关键字:quot 一个 视图 el 删除 backbone 何防止 remove      更新时间:2023-09-26

我想在创建一个新视图之前删除一个视图。但我的要求是view.remove()应该删除视图,但不删除el元素。话虽如此,我不想设置tagName,因为它创建了一个不必要的新元素。是否有任何方法从内存中删除视图,使el内容清除?

你可以在你的抽象视图中重写Backbone的view remove方法:

remove: function() {
  // this._removeElement();
  this.$el.empty();
  this.stopListening();
  return this;
}

默认源代码:http://backbonejs.org/docs/backbone.html#section-158

我以前用一次性启动器视图解决了这个问题。

确保你的HTML包含一个(class或id)锚为你的一次性视图:<div class="content-container"></div>

然后创建一个LauncherView:

var LauncherView = Backbone.View.extend({
    initialize: function(options) {
        this.render();
    },
    render: function() {
        this.$el.html(this.template());
        return this;
    },
    // inner views will be bound to ".launcher-container" via
    // their .el property passed into the options hash.
    template: _.template('<div class="launcher-container"></div>')
});

然后实例化你的一次性启动器视图:

app.currentLauncherView = new LauncherView({});

并将其附加到DOM锚:$('.content-container').append(app.currentLauncherView.el);

,那么你可以实例化一个视图,它将附加到一次性启动器视图:app.throwAway1 = new DisposableView({el: '.launcher-container'});

然后当你想要销毁这个视图时,你可以这样做:

app.throwAway1.off();
app.throwAway1.remove();
app.currentLauncherView.remove();

然后你可以通过实例化一个新的LauncherView来创建一个新的视图,将它附加到DOM上,并通过将它绑定到'来使你的下一个视图出现。launcher-container"。

app.currentLauncherView = new LauncherView({});
$('.content-container').append(app.currentLauncherView.el);
app.throwAway2 = new DisposableView({el: '.launcher-container'});
相关文章: