property-accessors1.1.3 • Public • Published
A mixin for defining dynamic properties.
To define a basic property accessor, use the
accessor declaration. If you've
included the mixin into a class, you define a prototype property by calling
@::accessor on its prototype.
PropertyAccessors = require 'property-accessors'PropertyAccessorsincludeIntothis@::accessor 'type': ->switch @doorCountwhen 4 then 'sedan' # i know this isn't strictly accuratewhen 2 then 'coupe':switch typewhen 'sedan' then @doorCount = 4when 'coupe' then @doorCount = 2car =car.doorCount = 2cartype # => 'coupe'
You can define a class-level property by extending with the mixin rather than including it (which extends the prototype).
PropertyAccessorsextendthis@accessor 'vehicleCount': -> @allVehicleslength
You can just pass a single function if you only want to define a getter:
PropertyAccessorsincludeIntothis@::accessor 'type'-> # ...
Lazy accessors call a function the first time a property is accessed. You are still free to overwrite this value by assigning the property explicitly.
PropertyAccessorsincludeIntothis@::lazyAccessor 'crazyComputation'-> computeCrazyComputation
Advised accessors allow you to call code before the reading or writing of a property value. If a property is being assigned, your advice function is called with the value being assigned and the old value.
@advisedAccessor 'online': -> @ensureAllSystemsNominal: -> @ensureUserIsSpystation =station.online = true # ensures user is a spy, then assigns truestationonline # ensures all systems are nominal, then returns true