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
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@tenedor
Copy link

tenedor commented Dec 29, 2012

Yup, I largely like this. It ties in better with having default values for things which are getter-only. In contrast with the current codebase, are there times when setting such default values into the data is desirable? Perhaps to keep the backend in sync? Perhaps so that if we change a property's default value, values in preexisting media don't change out from underneath a user?

also, a more robust version of the property method you're recommending:

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

@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