Setting default values for a Model in backbone.js
This will be a quick post on how to set, and work with default values in backbone. It sometimes just involves placing a defaults object of key and value pares, but things can become a little more complicated if you have a set method in the model.
What to know before hand
This is an advanced post on how to set up defaults for backbone Models, be sure to check out my Main post on Models if you want to know more about them in general. Also I you are new to backbone you will want to check out my getting start post on backbone as well.
The Need for defaults
When creating a new instance of a Model, I might pass an object that will set some attributes for that Models State, but maybe not, or maybe just a few values and not all of them. For any one or more values that are not set with the object that I give during the Models creation, there should be a hard coded default value that the constructor falls back onto. This is why it is wise to have a defaults object, or a function that creates one each time I make a new instance of the Model.
Set defaults with an object
The simplest way to set some defaults might be to just have a defaults object as part of the Model that is created with Backbone.Model.extend.
Set Model defaults with a function
Using a function will allow for dynamic defaults. This can be used in place of more complex methods of doing this, such as defining a custom constructor method.
backbone handles this aspect of making, and maintaining a Model well. It did not take me to log to get up to speed on how to do this, and I am moving on to more advanced aspects of MVC development with backbone.