Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store/push to an array in a Backbone Model

Tags:

backbone.js

I have this model defaults:

test.Models.ItemModel = Backbone.Model.extend({

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

Which I then use the following code to set the Model:

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

However, it never seems to get added to the Model array, am I doing things right here??

like image 814
benhowdle89 Avatar asked Nov 30 '12 11:11

benhowdle89


1 Answers

The problem is that you're assuming the the push method is returning the whole array; instead, as stated here, the push method

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

So, you need to push the element into the array before you set it to the model :

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

Careful though, this will modify anything else that points to this array, so if you do this, for example:

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 :(

If you want to avoid this, or still want to use a single line of code for that, you could use array's concat method:

this.model.set({ 
    'units' : this.model.get('units').concat($('#addUnit').val())
});
like image 185
gion_13 Avatar answered Oct 22 '22 10:10

gion_13