Backbone.js–Model Getter & Setter

Posted: June 1, 2014 in Javascript
Tags: , ,

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s