Javascript 为什么主干。视图对象仍保留在内存中?
我有一个显示对话框的简单视图Javascript 为什么主干。视图对象仍保留在内存中?,javascript,backbone.js,underscore.js,javascript-framework,Javascript,Backbone.js,Underscore.js,Javascript Framework,我有一个显示对话框的简单视图 Backbone.View.prototype.completeRemove = function(){ this.undelegateEvents(); this.remove(); delete this.$el; delete this.el; console.log('completely removed') } MdApp.dialogBox = Backbone.View.extend({ defaul
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();
}
});
在此之后,我将调用另一个对话框,但该对话框没有cancelable
属性,因此它应该使用默认对话框(即false
),但它保持为true。这适用于所有其他财产。为什么会发生这种情况?来自:
扩展扩展(目的地,*来源)
将源对象中的所有属性复制到目标对象,并返回目标对象
这意味着。
修改o
。所以当你这样做的时候:
this.model = _.extend(this.defaults, this.model);
您正在有效地这样做:
for(k in this.model)
this.defaults[k] = this.model[k];
this.model = this.defaults;
默认值
已附加到原型,因此您实际上正在更改默认值
,该默认值将由MdApp.dialogBox的每个实例共享。这就是为什么您最终会得到粘性属性:您正在将所有不同的this.model
s合并到视图原型上的默认值中
你可以这样做:
// Merge into an empty object to avoid altering this.defaults
this.model = _.extend({}, this.defaults, this.model);
或者您可以使用而不是。扩展:
默认值默认值(对象,*默认值)
用默认值对象中的值填充对象中的空属性和未定义属性,并返回对象。一旦该属性被填充,进一步的默认设置将不起作用
所以你可以这样做:
_(this.model).defaults(this.defaults);
这将改变This.model
,因此您的视图将假设它完全拥有This.model
,并且没有任何外部引用到该对象
_(this.model).defaults(this.defaults);