Suffix

Simple getters in Backbone.js

Overriding default Backbone getter to more complex logic.

There is an easy way to get your Backbone.js model attributes:

person = new Person({firstName: "John", lastName: "Doe"});
person.get('firstName');

Overriding getters

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:

Person =  Backbone.Model.extend({
  name: function() {
    return this.firstName + " " + this.lastName;
  }
});

The function on itself isn't enough to have a nice getter as we have for the ‘normal’ attributes above, let's fix that:

Person =  Backbone.Model.extend({
  get: function (attr) {
    if (typeof this[attr] == 'function') {
      return this[attr]();
    }
    return Backbone.Model.prototype.get.call(this, attr);
  },

  name: function() {
    return this.firstName + " " + this.lastName;
  }
});

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.

toJSON

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.

Person =  Backbone.Model.extend({
  get: function (attr) {
    if (typeof this[attr] == 'function') {
      return this[attr]();
    }
    return Backbone.Model.prototype.get.call(this, attr);
  },

  name: function() {
    return this.firstName + " " + this.lastName;
  },

  toJSON: function() {
    var attr = Backbone.Model.prototype.toJSON.call(this);
    attr.name = this.name();
    return attr;
  }
});

That’s it, you now have access to person.get("name") wherever you need.

Read more