The Model module provides helper methods to compose nested data models.
Models uses Observable to keep the internal data in sync.
Core = require "core"
Observable = require "observable"
module.exports = (I={}, self=Core(I)) ->
self.extendObserve any number of attributes as simple observables. For each attribute name passed in we expose a public getter/setter method and listen to changes when the value is set.
attrObservable: (names...) ->
names.forEach (name) ->
self[name] = Observable(I[name])
self[name].observe (newValue) ->
I[name] = newValue
return selfObserve an attribute as a model. Treats the attribute given as an Observable model instance exposting a getter/setter method of the same name. The Model constructor must be passed in explicitly.
attrModel: (name, Model) ->
model = Model(I[name])
self[name] = Observable(model)
self[name].observe (newValue) ->
I[name] = newValue.I
return selfObserve an attribute as a list of sub-models. This is the same as attrModel
except the attribute is expected to be an array of models rather than a single one.
attrModels: (name, Model) ->
models = (I[name] or []).map (x) ->
Model(x)
self[name] = Observable(models)
self[name].observe (newValue) ->
I[name] = newValue.map (instance) ->
instance.I
return selfattrDatum models an attribute as a data object. For example if our object has
a position attribute with x and y values we can do
self.attrDatum("position", Point)
to promote the raw data into a Point data model available through a public observable named position.
attrDatum: (name, DataModel) ->
I[name] = model = DataModel(I[name])
self[name] = Observable(model)
self[name].observe (newValue) ->
I[name] = newValue
return selfattrData models an array attribute as an observable array of data objects.
attrData: (name, DataModel) ->
models = (I[name] or []).map (x) ->
DataModel(x)
self[name] = Observable(models)
self[name].observe (newValue) ->
I[name] = newValue.map (x) ->
DataModel(x)
return selfThe JSON representation is kept up to date via the observable properites and resides in I.
toJSON: ->
IReturn our public object.
return self