微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有这个模型认值:
test.Models.Itemmodel = Backbone.Model.extend({

defaults: {
    name: 'an item',units: []
},

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

addUnit: function(e){
    if(e.keyCode == 13){
      this.model.set({ 'units' : this.model.get('units').push($('#addUnit').val()) },{success: function(){
          this.render();
        }}
      );
    }
  },

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

解决方法

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

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

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

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

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

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

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

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

原文地址:https://www.jb51.cc/js/150061.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐