Getters and Setters for Backbone Model attributes

Oct 16, 2011 Backbone.jscoffeescript

The Backbone.js Model class provides get and set methods to read and write Model attributes which is not a concise or natural as object property access. But it’s not difficult to add a class method to generate Model getter/setter properties so that you can do this in CoffeeScript: = 'Joe Bloggs'
ph =

instead of this:

person.set {name: 'Joe Bloggs'}
ph = person.get 'name'

The CoffeeScript example below shows how it’s done using the ECMAScript 5 Object.defineProperty function to define a Model attribute method. I’ve added the attribute class method to a BaseModel class which is inherited by application classes. To create a Model attribute property call the attribute method and pass it the name of the property.

    Backbone = require 'backbone'
    class BaseModel extends Backbone.Model
        # Create model attribute getter/setter property.
        @attribute = (attr) ->
            Object.defineProperty @prototype, attr,
                get: -> @get attr
                set: (value) ->
                    attrs = {}
                    attrs[attr] = value
                    @set attrs
    class Contact extends BaseModel
        @attribute 'name'
        @attribute 'phone'
    p = new Contact() = 'Joe Bloggs' = '1234'
    console.log p.attributes    # { name: 'Joe Bloggs', phone: '1234' }

Being able to create custom getter/setter properties is a testament to the little known power of JavaScript.


« Previous Next »