Skip to content

Instantly share code, notes, and snippets.

@jbenet
Forked from anonymous/model.coffee
Last active December 10, 2015 04:38
Show Gist options
  • Save jbenet/4382549 to your computer and use it in GitHub Desktop.
Save jbenet/4382549 to your computer and use it in GitHub Desktop.
class Model
constructor: ->
@data = {}
set: (key, val) ->
@data[key] = val
get: (key) ->
@data[key]
@property: (property, options={setter:true}) ->
(value) ->
if options.setter? and value?
@set property, value
@get(property) ? options.default
class Foo extends Model
foo: @property 'foo'
bar: @property('bar', setter:false)
baz: @property('baz', default:'Baz')
f = new Foo()
f.foo('fa')
console.log f.foo()
console.log f.data
f.data.foo = 'fb'
console.log f.foo()
console.log f.data
f.bar('ba')
console.log f.bar()
console.log f.data
f.data.bar = 'bb'
console.log f.bar()
console.log f.data
console.log f.baz()
console.log f.data
f.baz('ca')
console.log f.baz()
console.log f.data
f.data.baz = 'cb'
console.log f.baz()
console.log f.data
@jbenet
Copy link
Author

jbenet commented Dec 29, 2012

Re default: yeah, indeed.

Re setter: ah yes, good point! maybe even:

class Model
  @property: (property, options={}) ->
    options.setter ?= true
    (value) ->
      if options.setter and value?
        @set property, value
      @get(property) ? options.default

@tenedor
Copy link

tenedor commented Dec 29, 2012

you're probably right that {setter: undefined} should not be considered a request for getter-only. simplest of all is just options.setter != false, it's fine if we ignore 0 and ''

@jbenet
Copy link
Author

jbenet commented Dec 29, 2012

sounds good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment