Created
November 15, 2012 17:28
-
-
Save ndnichols/4079943 to your computer and use it in GitHub Desktop.
A function for automatically adding getter/setters to Backbone models.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{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} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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