backbone.js – 存储/推送到Backbone模型中的数组

前端之家收集整理的这篇文章主要介绍了backbone.js – 存储/推送到Backbone模型中的数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个模型默认值:
  1. test.Models.ItemModel = Backbone.Model.extend({
  2.  
  3. defaults: {
  4. name: 'an item',units: []
  5. },

然后我使用以下代码来设置模型:

  1. addUnit: function(e){
  2. if(e.keyCode == 13){
  3. this.model.set({ 'units' : this.model.get('units').push($('#addUnit').val()) },{success: function(){
  4. this.render();
  5. }}
  6. );
  7. }
  8. },

但是,它似乎永远不会被添加到Model数组中,我在这里做事吗?

解决方法

问题是你假设push方法返回整个数组;相反,as stated here,推方法

Returns the new length property of the object upon which the method was called.

因此,在将元素设置为模型之前,需要将元素推入数组:

  1. var _units = this.model.get('units');
  2. _units.push($('#addUnit').val());
  3. this.model.set({ 'units' : _units });

但是要小心,这将修改指向此数组的任何其他内容,因此如果您这样做,例如:

  1. var myArray = [1,2,3]
  2. this.model.set({units: myArray})
  3. var _units = this.model.get('units')
  4. _units.push(4)
  5. this.model.set({ 'units' : _units })
  6. myArray == this.model.get('units') // holy moly,they're the same :(

如果你想避免这种情况,或者仍然想要使用单行代码,你可以使用数组的concat method

  1. this.model.set({
  2. 'units' : this.model.get('units').concat($('#addUnit').val())
  3. });

猜你在找的JavaScript相关文章