浅谈Backbone的defaults

使用Backbone开发也有一段时间了,直到前2周,才发现,之前走的都是弯路,使用的方式都是错的。

不扯了。今天记录一下自己使用Backbone的defaults时需要注意的地方。

 

用过Backbone的都知道,defaults能节省不少重复的初始化代码段。

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();

 

然后试试下面的代码

 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);

结果如下

 

 

是的,Model b的数据也改了,原因很简单:Array和Object是引用类型。

 

解决方法:

1,初始化对象时,显式传入初始化的数据

1 var a = new Model({ list: [], obj: {} });
2 var b = new Model({ list: [], obj: {} });

2,在Model的initialize方法中设置默认值

1 var Model = Backbone.Model.extend({
2     initialize: function () {
3         this.set({
4             list: [],
5             obj: {}
6         });
7     }
8 });

3,修改defaults对象的值,通过function返回

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

 

 

仅此提醒自己:不要想着看文档就行,无需理会源码。真的不能再偷懒了!

 

posted @ 2014-12-09 15:43  Larify  阅读(286)  评论(0编辑  收藏  举报