In my last post, we have seen how to define models in Backbone.js and create instances of their objects.In this post we will see how we can set & get attribute values in Backbone.js model.Backbone.Model exposes two functions set and get to do so. The code snippet below shows the use of these functions.
The code below tries to access one non-existent attribute’s (“c” in this case) value which obviously will return undefined.
We can handle this situation in an elegant way using the has function. The has function returns true/false based on whether a property exists or not.
The attributes attribute and the toJSON function returns the dump of the attributes & the value in JSON format. The code below will print “Object { a=2, b=4, c=5}”.
The unset function removes a particular attribute from the object hash.
The clear function will clear the entire object hash removing all the attributes.
So now we have covered mostly all the Backbone.js functions related to attribute manipulation. However we can provide model specific functions for getting/setting attributes instead of directly using the get & set methods as shown below.
In the next post, we will move change listeners and tracking in the model.