繁体   English   中英

如何防止主干remove()在视图中删除“el”?

[英]How do I prevent backbone remove() from removing “el” in a view?

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

您可以在抽象视图中覆盖Backbone的视图remove方法:

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

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

我之前用一次性发射器视图解决了这个问题。

确保你的html包含一次性视图的(类或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'});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM