簡體   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