Skip to content

Instantly share code, notes, and snippets.

@cohei
Last active August 29, 2015 14:04
Show Gist options
  • Save cohei/c1621b0e29f406bfabf7 to your computer and use it in GitHub Desktop.
Save cohei/c1621b0e29f406bfabf7 to your computer and use it in GitHub Desktop.
Backbone のモデルでプロパティのように属性にアクセスする
# 参考: http://www.narrativescience.com/blog/automatically-creating-getterssetters-for-backbone-models/
buildProperties = (model) ->
buildGetter = (name) -> () -> model.get name
buildSetter = (name) -> (value) -> model.set name, value
for attribute in _.keys model.defaults
Object.defineProperty model, attribute,
get: buildGetter attribute
set: buildSetter attribute
Person = Backbone.Model.extend
initialize: ->
buildProperties @
defaults:
name: undefined
age: undefined
p = new Person name: 'R', age: 20
p.name #=> "R"
p.age = 30
p.age #=> 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment