Skip to content

Instantly share code, notes, and snippets.

@ndnichols
Created November 15, 2012 17:28
Show Gist options
  • Save ndnichols/4079943 to your computer and use it in GitHub Desktop.
Save ndnichols/4079943 to your computer and use it in GitHub Desktop.
A function for automatically adding getter/setters to Backbone models.
buildProperties = (func) ->
buildGetter = (name) ->
-> @get name
buildSetter = (name) ->
(value) -> @set name, value
for attr in func.prototype.attributeNames
Object.defineProperty func.prototype, attr,
get: buildGetter attr
set: buildSetter attr
exports.buildProperties = buildProperties
{buildProperties} = require './buildProperties'
backbone = require 'backbone'
class Character extends backbone.Model
attributeNames: ['name', 'age']
buildProperties @
guy = new Character
name: 'Guybrush'
age: 20
console.log guy.get 'name' # "Guybrush"
console.log guy.name # "Guybrush"
guy.name = 'Murray'
console.log guy.name # "Murray"
guy.age++
console.log guy.age # 21
console.log guy.attributes # {'name':'Murray', 'age':21}
guy = new Person
name: 'Guybrush'
elaine = new Person
name: 'Elaine'
guy.spouse = elaine
elaine.spouse = guybrush
guy.spouse is elaine # true
console.log guy.attributes # {'spouse':42}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment