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 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())
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With