Created
December 30, 2011 08:14
-
-
Save KrofDrakula/1538645 to your computer and use it in GitHub Desktop.
Getters and setters for 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
Backbone = require 'backbone' | |
class BaseModel extends Backbone.Model | |
constructor: -> | |
super | |
model = @ | |
@data = data = {} | |
for key of @defaults | |
do (key) -> | |
data.__defineGetter__ key, -> | |
model.get key | |
data.__defineSetter__ key, (value) -> | |
d = {} | |
d[key] = value | |
model.set d | |
module.exports = BaseModel |
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
BaseModel = require 'BaseModel' | |
# To register getters and setters, BaseModel requires you | |
# to declare properties in the `defaults` property | |
class Person extends BaseModel | |
defaults: | |
firstName : null | |
lastName : null | |
phone : null | |
mike = new Person firstName: 'Mike', lastName: 'Wieringo', phone: 'unlisted' | |
# Use getters via `data` property | |
alert "Person's firstName is #{mike.data.firstName}" | |
# Bind events and watch them fira via setters | |
mike.bind 'change:phone', (ev) -> alert "#{mike.data.firstName} changed his phone number!" | |
mike.data.phone = '0-800-WIERINGO' |
True enough, but it did support the target browsers we were using. I'll think about getting a wider and proper support for this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is a non standard extension. The correct ES5 code is