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 powerful. 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 convenience 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 now have access to person.get("name") wherever you need.
- Big thanks to Eric Howe for helping me out with this one on StackOverflow.