How not to set Backbone model properties

So here is another backbone.js tidbit that took me a while to figure out/understand. This may be fairly straight forward to seasoned programmers, but it really through me for a loop. If you try and set initial model (or view) properties outside of the “defaults” method you can not retrieve them using model.get(‘propertyName’). This was a point of confusion because sometimes it was working like i though it should and sometimes it did not. To further complicate things I was trying to set properties by passing them when I was instantiating the object. It took me a while to figure out what I was doing wrong.

So this is incorrect even though you can still access the object properties.


ExampleModel = Backbone.Model.extend({
propertyName: 'Some Value',
})
exampleModel = new ExampleModel ({propertyName: 'Updated Value'});
exampleModel.propertyName// 'Some Value' not 'Updated Value'

From what I understand this is the correct way to do it


ExampleModel = Backbone.Model.extend({
defaults: {
propertyName: 'Some Value',
},
})
exampleModel = new ExampleModel ({propertyName: 'Updated Value'});
exampleModel.get('propertyName') //'Updated Value'

Now that I understand the concept the documentation makes this very clear to correctly set default model properties using the defaults method.

Comments are closed.