0

我有簡單的視圖,顯示對話框。爲什麼Backbone.View對象仍然保留在內存中?

Backbone.View.prototype.completeRemove = function(){ 
    this.undelegateEvents(); 
    this.remove(); 
    delete this.$el; 
    delete this.el; 
    console.log('completely removed') 
} 

MdApp.dialogBox = Backbone.View.extend({ 

    defaults: { 
     text: __('No text provided'), 
     buttonText: __('Ok'), 
     callback: function(){ 
      return null; 
     }, 
     el: $('#app-panel'), 
     type: 'error', 
     cancellable: false, 
     cancelText: __('No'), 
     picture: pic('default') 
    }, 

    el: '<div class="dialog-box">', 

    template: _.template($('#dialog-box-template').html()), 

    events: { 
     'click .confirm' : 'confirm', 
     'click .cancel' : 'cancel' 
    }, 

    initialize: function(){ 
     this.model = _.extend(this.defaults, this.model); 
     this.render(); 
    }, 

    render: function(){ 
     var model = this.model; 
     this.$el.html(this.template(model)); 
     model.el.append(this.el); 
    }, 

    confirm: function(){ 
     var model = this.model; 
     var view = this; 
     this.completeRemove(); 
     model.callback(); 
    }, 

    cancel: function(){ 
     this.completeRemove(); 
    } 
}); 

它有它自己的默認值。每次我初始化新對話框時,它的值在每次對話框調用之間都會持續存在。例如,當我調用對話首次:

new MdApp.dialogBox({model:{ 
     text: __('Do you really wanna delete this?'), 
     buttonText: __('Unfortunately yes'), 
     callback: function(){ 
      //some callback 
     }, 
     cancellable: true, 
     cancelText: __('No'), 
     picture: pic('confirm delete') 
    }}); 

在那之後,我調用另一個對話框,不cancellable屬性,因此它應該使用默認的(這是false),但它保持真實。這適用於所有其他財產。爲什麼會發生?

回答

2

fine manual

延伸_.extend(destination, *sources)

複製所有在源屬性對象轉移到目的地對象,並返回目的地對象。

這意味着_.extend(o, ...)修改爲o。所以,當你這樣做:

this.model = _.extend(this.defaults, this.model); 

你有效地這樣做:

for(k in this.model) 
    this.defaults[k] = this.model[k]; 
this.model = this.defaults; 

defaults連接到原型,以你的,其實,改變將由每個實例共享的defaultsMdApp.dialogBox。這就是爲什麼你最終會遇到粘性屬性:你將所有各種this.model s合併到視圖原型中的defaults

你可以做這樣的:

// Merge into an empty object to avoid altering this.defaults 
this.model = _.extend({}, this.defaults, this.model); 

或者你可以使用_.defaults代替_.extend

默認值在零和未定義的屬性_.defaults(object, *defaults)

填寫對象,其值爲默認對象,並返回對象。一旦財產被填補,進一步的違約將不會生效。

所以,你可以這樣做:

_(this.model).defaults(this.defaults); 

這將改變就地this.model所以你的觀點會被假定它全資擁有this.model,並且不會有到該對象的任何外部引用。

相關問題