你试图做什么没有任何意义。你defaults
是保存单个对象的数组:
defaults: {
attrArray: [
{ item_id: '', type: '', name: '' }
]
},
你会使用一个数组,如果你想坚持的属性对象的列表。但是,如果你有一个属性对象列表,你期望attrArray['item_id']
可以引用哪一个item_id
?您是否假设attrArray
将始终初始化为默认值,并且没有人会发送attrArray
作为模型初始数据的一部分?如果是这样,你想要更多的东西是这样的:
// Use a function so that each instance gets its own array,
// otherwise the default array will be attached to the prototype
// and shared by all instances.
defaults: function() {
return {
attrArray: [
{ item_id: '', type: '', name: '' }
]
};
},
initialize: function() {
// get will return a reference to the array (not a copy!) so
// we can modify it in-place.
this.get('attrArray')[0]['item_id'] = this.cid;
}
注意,你会碰到需要特殊处理的一些问题与阵列属性:
get('attrArray')
将参考返回数组那就是在模型内部,所以修改返回值会改变模型。
- 之类的东西
a = m.get('attrArray'); a.push({ ... }); m.set('attrArray', a)
将无法正常工作,你指望他们的set
不会注意到该数组已经改变(因为它有没有,a == a
毕竟是真实的)的方式,所以你不会得到"change"
事件,除非你可以在get
和set
之间的某个地方克隆attrArray
。
d'oh!我删除了数组包装,因为它对我没有意义:P –