-
-
Save jbenet/4382549 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 |
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
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 ''
sounds good
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: