Browse files

Default values for properties

  • Loading branch information...
1 parent 0344a77 commit a03d7804b4a6ae3fef0b0de9f2198c0ed16c966a @jnicklas jnicklas committed Jun 6, 2012
Showing with 20 additions and 0 deletions.
  1. +3 −0 src/properties.coffee
  2. +17 −0 test/properties.spec.coffee
View
3 src/properties.coffee
@@ -63,6 +63,7 @@ Serenade.Properties =
property: (name, options={}) ->
@[prefix + name] = options
@[prefix + name].name = name
+ @[prefix + name].default = @[name] if @.hasOwnProperty(name)
addDependencies(this, name, options.dependsOn) if options.dependsOn
if define
Object.defineProperty @, name,
@@ -104,6 +105,8 @@ Serenade.Properties =
@attributes or= {}
value = if @[prefix + name]?.get
@[prefix + name].get.call(this)
+ else if @[prefix + name]?.hasOwnProperty("default") and not @attributes.hasOwnProperty(name)
+ @[prefix + name].default
else
@attributes[name]
View
17 test/properties.spec.coffee
@@ -54,6 +54,23 @@ describe 'Serenade.Properties', ->
@inst1.property 'age', serialize: true
@inst2.property 'height', serialize: true
expect(Object.keys(@inst2.serialize())).not.to.include('age')
+ it 'can set up default value', ->
+ @object.property 'name', default: "foobar"
+ expect(@object.name).to.eql("foobar")
+ @object.name = "baz"
+ expect(@object.name).to.eql("baz")
+ @object.name = undefined
+ expect(@object.name).to.eql(undefined)
+ it 'can set up falsy default values', ->
+ @object.property 'name', default: null
+ expect(@object.name).to.equal(null)
+ it 'ignores default when custom getter given', ->
+ @object.property 'name', default: "bar", get: -> "foo"
+ expect(@object.name).to.eql("foo")
+ it 'automatically sets up previous value as default', ->
+ @object.name = "Jonas"
+ @object.property 'name'
+ expect(@object.name).to.eql("Jonas")
describe '.collection', ->
it 'is initialized to a collection', ->

1 comment on commit a03d780

@cjse
Elabs member

Very nice!

Please sign in to comment.