问题描述
我正在尝试在ribs.js模型的初始化函数中设置数组值.在以"this.set ..."开头的行中,出现意外字符串"错误.这样无法设置数组值吗?
I'm trying to set an array value in a backbone.js model initialize function. In the line that starts with 'this.set...' I get a 'unexpected string' error. Is it not possible to set array values this way?
谢谢!
var bGenericItem = Backbone.Model.extend({
defaults: {
attrArray: new Array({'item_id': '', 'type': '', 'name':''})
},
initialize: function(){
// Set the id to cid for now
this.set({ attrArray["item_id"]: this.cid });
}
});
推荐答案
您尝试执行的操作没有任何意义.您的 defaults
是一个包含单个对象的数组:
What you're trying to do doesn't make any sense. Your defaults
is an array which holds a single object:
defaults: {
attrArray: [
{ item_id: '', type: '', name: '' }
]
},
如果要保存属性对象列表,则可以使用数组.但是,如果您有一个属性对象列表,您希望 attrArray ['item_id']
引用哪个对象?您是否假设将 attrArray
始终初始化为默认值,并且没有人会在模型的初始数据中发送 attrArray
?如果是这样,您想要更多类似这样的东西:
You'd use an array if you wanted to hold a list of attribute objects. But, if you had a list of attribute objects, which one's item_id
would you expect attrArray['item_id']
to refer to? Are you assuming that attrArray
will always be initialized to the default value and that no one would ever send an attrArray
in as part of your model's initial data? If so, you'd want something more like this:
// 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;
}
请注意,您将遇到需要特殊处理的数组属性问题:
Note that you'll run into some issues with array attributes that require special handling:
-
get('attrArray')
将返回对模型内部数组的引用,因此修改返回值将更改模型. - 类似
a = m.get('attrArray');的东西a.push({...});m.set('attrArray',a)
不会像您期望的那样工作,set
不会注意到数组已更改(因为它没有更改,a == a
毕竟是真的),因此除非您将attrArray
克隆在之间的某个地方,否则您不会获得
和"change"
事件获取设置
.
get('attrArray')
will return a reference to the array that is inside the model so modifying that return value will change the model.- Things like
a = m.get('attrArray'); a.push({ ... }); m.set('attrArray', a)
won't work the way you expect them to, theset
won't notice that the array has changed (because it hasn't,a == a
is true after all) so you won't get"change"
events unless you clone theattrArray
somewhere betweenget
andset
.
这篇关于在ribs.js初始化函数中设置数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!