There is an easy way to get your Backbone.js model attributes:
This is all great if all you need is a simple getter but you quickly want to get something more powerfull. What if you want to show the persons full name, his first and last name combined? You could simply concatenate both attributes in your template but that gets annoying quickly. What we want is a convienience function on the model to get the full name.
No problem, simply add an extra function:
The function on itself isn't enough to have a nice getter as we have for the ‘normal’ attributes above, let's fix that:
By overriding the Backbone.js getter function and adding the functions as well we can now call the full person name in a similar fashion as the other attributes and don't worry how to format it.
The main disadvantage here is the toJSON function Backbone.js provides to serialize your models and collections. It's commonly used before sending your data to the templates. Our name function won't be included as it's not a real attribute of the model. We can fix this by also overriding the toJSON function and tell it about our name function.
That's it, you have now access to person.get("name") wherever you need.
This post is open source. Did you spot a mistake? Ideas for improvements? Contribute to this post via Github. Thank you!