繁体   English   中英

销毁或删除 Backbone.js 中的视图

[英]Destroy or remove a view in Backbone.js

我目前正在尝试为视图实现销毁/删除方法,但我无法获得适用于所有视图的通用解决方案。

我希望有一个事件可以附加到 controller,这样当一个新请求通过时,它会破坏以前的视图,然后加载新的视图。

有什么方法可以做到这一点而不必为每个视图构建删除 function ?

我必须绝对确定视图不仅从 DOM 中删除,而且还完全不受事件的约束。

destroy_view: function() {

    // COMPLETELY UNBIND THE VIEW
    this.undelegateEvents();

    this.$el.removeData().unbind(); 

    // Remove view from DOM
    this.remove();  
    Backbone.View.prototype.remove.call(this);

}

对我来说似乎有点矫枉过正,但其他方法并没有完全奏效。

在不知道所有信息的情况下...您可以将重置触发器绑定到 model 或 controller:

this.bind("reset", this.updateView);

当你想重置视图时,触发重置。

对于您的回调,请执行以下操作:

updateView: function() {
  view.remove();
  view.render();
};

我知道我迟到了,但希望这对其他人有用。 如果您使用主干 v0.9.9+,您可以使用、 listenTostopListening

initialize: function () {
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.model, 'destroy', this.remove);
}

stopListeningremove自动调用。 你可以在这里这里阅读更多

这是我一直在使用的。 没有看到任何问题。

destroy: function(){
  this.remove();
  this.unbind();
}

根据当前的 Backbone 文档....

view.remove()

从 DOM 中删除视图及其 el,并调用 stopListening 以删除视图已监听的任何绑定事件。

我认为这应该有效

destroyView : function () {
    this.$el.remove();
}

你可以用这个方法来解决问题!

initialize:function(){
    this.trigger('remove-compnents-cart');
    var _this = this;
    Backbone.View.prototype.on('remove-compnents-cart',function(){
        //Backbone.View.prototype.remove;
        Backbone.View.prototype.off();
        _this.undelegateEvents();
    })
}

另一种方式:创建一个全局变量,像这样: _global.routerList

initialize:function(){
    this.routerName = 'home';
    _global.routerList.push(this);
}
/*remove it in memory*/
for (var i=0;i<_global.routerList.length;i++){
    Backbone.View.prototype.remove.call(_global.routerList[i]);
}

暂无
暂无

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

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