Getters and Setters for Backbone Model attributes

Published: 2011-10-16

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:

person.name = 'Joe Bloggs'
ph = person.phone

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()
p.name = 'Joe Bloggs'
p.phone = '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.

References

About these ads

One Response to “Getters and Setters for Backbone Model attributes”

  1. duskieskrat Says:

    Nice, this should be there by default, here’s pure JS version, it uses Backbone.Model.defaults though. https://gist.github.com/3181775

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s


%d bloggers like this: