2013-01-23 37 views
0

我想在backbone.js模型初始化函数中设置一个数组值。在以'this.set ...'开头的行中,我得到一个'意外的字符串'错误。以这种方式设置数组值不可能吗?在backbone.js初始化函数中设置数组值

谢谢!

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

回答

2

你试图做什么没有任何意义。你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; 
} 

注意,你会碰到需要特殊处理的一些问题与阵列属性:

  1. get('attrArray')将参考返回数组那就是在模型内部,所以修改返回值会改变模型。
  2. 之类的东西a = m.get('attrArray'); a.push({ ... }); m.set('attrArray', a)将无法​​正常工作,你指望他们的set不会注意到该数组已经改变(因为它有没有,a == a毕竟是真实的)的方式,所以你不会得到"change"事件,除非你可以在getset之间的某个地方克隆attrArray
1

有几个问题与您的代码

1:defaults设置为对象文本,这意味着分配给它,一旦它被定义设置的值。您需要将您的默认值设置为一个函数,而不是文字值。这将确保每个模型实例获取它自己的默认值副本,而不是在每个模型实例之间共享副本。

2:您也不应该使用new Array,只需使用数组字面语法[]即可。但是你并没有真的在这段代码中使用数组,所以现在我删除了数组封装。你可以直接访问attrArray。你必须从模型的属性中得到它,然后更新它


var bGenericItem = Backbone.Model.extend({ 

    defaults: function(){ 
     return { 
     attrArray: {'item_id': '', 'type': '', 'name':''} 
     }; 
    }, 
    initialize: function(){ 
     // Set the id to cid for now 
     var arr = this.get("attrArray"); 
     arr["item_id"] = this.cid; 
    } 
}); 
+0

d'oh!我删除了数组包装,因为它对我没有意义:P –