使用Backbone開發也有一段時間了,直到前2周,才發現,以前走的都是彎路,使用的方式都是錯的。git
不扯了。今天記錄一下本身使用Backbone的defaults時須要注意的地方。github
用過Backbone的都知道,defaults能節省很多重複的初始化代碼段。app
1 var Model = Backbone.Model.extend({ 2 defaults: { 3 str: 'this is string', 4 num: 0 5 } 6 }); 7 8 var a=new Model(); 9 var b=new Model();
而後試試下面的代碼this
1 var Model = Backbone.Model.extend({ 2 defaults: { 3 list: [], 4 obj: {} 5 } 6 }); 7 8 var a = new Model(); 9 var b = new Model(); 10 11 a.get('list').push(1); 12 a.get('obj')['str'] = 'tihs is string'; 13 14 console.log("b.attributes", b.attributes);
結果以下spa
是的,Model b的數據也改了,緣由很簡單:Array和Object是引用類型。code
解決方法:對象
1,初始化對象時,顯式傳入初始化的數據blog
1 var a = new Model({ list: [], obj: {} }); 2 var b = new Model({ list: [], obj: {} });
2,在Model的initialize方法中設置默認值backbone
1 var Model = Backbone.Model.extend({ 2 initialize: function () { 3 this.set({ 4 list: [], 5 obj: {} 6 }); 7 } 8 });
3,修改defaults對象的值,經過function返回ci
1 var Model = Backbone.Model.extend({ 2 defaults: function () { 3 return { 4 list: [], 5 obj: {} 6 }; 7 } 8 });
看Backbone的Model方法
1 var Model = Backbone.Model = function(attributes, options) { 2 var attrs = attributes || {}; 3 options || (options = {}); 4 this.cid = _.uniqueId('c'); 5 this.attributes = {}; 6 if (options.collection) this.collection = options.collection; 7 if (options.parse) attrs = this.parse(attrs, options) || {}; 8 attrs = _.defaults({}, attrs, _.result(this, 'defaults')); 9 this.set(attrs, options); 10 this.changed = {}; 11 this.initialize.apply(this, arguments); 12 };
重點是:attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
其中的Underscore方法_.result
僅此提醒本身:不要想着看文檔就行,無需理會源碼。真的不能再偷懶了!