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??
The problem is that you’re assuming the the
pushmethod is returning the whole array; instead, as stated here, thepushmethodSo, you need to push the element into the array before you set it to the model :
Careful though, this will modify anything else that points to this array, so if you do this, for example:
If you want to avoid this, or still want to use a single line of code for that, you could use array’s
concatmethod: