app/assets/javascripts/luca/concerns/state_model.coffee in luca-0.9.8 vs app/assets/javascripts/luca/concerns/state_model.coffee in luca-0.9.9
- old
+ new
@@ -1,44 +1,58 @@
+
+stateModel = Luca.register("Luca.ViewState").extends("Luca.Model")
+
Luca.concerns.StateModel =
+ __onModelChange: (args...)->
+ statefulView = @
+ state = statefulView.state
+
+ @trigger.call(statefulView, "state:change", args... )
+
+ for changed, value of state.changedAttributes()
+ @trigger.call statefulView, "state:change:#{ changed }", state, value, state.previous(changed)
+
__initializer: ()->
@stateful = @stateAttributes if @stateAttributes?
return unless @stateful?
- return if @state?
+ statefulView = @
+
if _.isObject(@stateful) and not @defaultState?
@defaultState = @stateful
- @state = new Backbone.Model(@defaultState || {})
- @set = _.bind(@state.set, @state)
- @get = _.bind(@state.get, @state)
+ @state ||= new Luca.ViewState(@defaultState || {})
+ view = @
+
+ @get = ()->
+ view.state.get.apply(view.state, arguments)
+
+ @set = ()->
+ view.state.set.apply(view.state, arguments)
+
for key, value of @state.toJSON()
hook = "on" + _.str.capitalize(key) + "Change"
getter = "get" + _.str.capitalize(key)
unless _.isFunction(@[getter])
1
- #console.log("State Change Getter", getter)
- # @[getter] = ()=> @state.get(key)
- # WE COULD CREATE AUTO GETTERS HERE
-
if _.isFunction(@[hook])
1
- #console.log("State Change Hook", hook)
- # @stateChangeEvents[ key ] = hook
- # WE COULD AUTO BIND TO STATE CHANGE EVENTS HERE
- unless _.isEmpty(@stateChangeEvents)
- for attribute, handler of @stateChangeEvents
- fn = if _.isString(handler) then @[handler] else handler
-
- if attribute is "*"
- @on "state:change", fn, @
- else
- @on "state:change:#{ attribute }", fn, @
+ Luca.concerns.StateModel.__setupModelBindings.call(@, "on")
- @state.on "change", (state)=>
- @trigger "state:change", state
+ __setupModelBindings: (direction="on")->
+ statefulView = @
+ for attribute, handler of @stateChangeEvents
+ fn = if _.isString(handler) then statefulView[handler] else handler
+
+ if attribute is "*"
+ statefulView[direction]("state:change", fn, statefulView)
+ else
+ statefulView[direction]("state:change:#{ attribute }", fn, statefulView)
- for changed, value of state.changedAttributes()
- @trigger "state:change:#{ changed }", state, value, state.previous(changed)
-
+ # Any time there is a model change event on the internal state machine
+ # we will trigger a general state:change event on the component as well
+ # as individual state:change:attribute events
+ state = statefulView.state
+ statefulView.state[direction]("change", Luca.concerns.StateModel.__onModelChange, statefulView)