Skip to content

Instantly share code, notes, and snippets.

@androidStern
Created July 11, 2014 18:12
Show Gist options
  • Select an option

  • Save androidStern/72671f88894c005574e5 to your computer and use it in GitHub Desktop.

Select an option

Save androidStern/72671f88894c005574e5 to your computer and use it in GitHub Desktop.
EE = require 'wildemitter'
class Observable extends EE
constructor: (initialValue)->
_latestValue = initialValue
@_write = (_next_val)=>
@emit "will-change", _latestValue, (=>
_latestValue = _next_val
@emit "changed", _latestValue
)
@_read = -> _latestValue
EE.call(this)
class Model extends EE
constructor: (props)->
# inherit from Event emitter
EE.call(this)
_undo_stack = []
self = this
state_callbacks = {}
@getState = ->
_o = {}
for k,v of state_callbacks
_o[k] = v._read()
return _o
@getHistory = ->
_undo_stack.concat @getState()
for k,v of props
do (k = k ,v = v)->
o = new Observable(v)
o.on "will-change", (val, cb)->
_undo_stack.push self.getState()
cb()
o.on "changed", ->
self.emit "change", self.getState()
self[k] = (args...)->
if args.length > 0
o._write(args[0])
else
o._read()
state_callbacks[k] = o
z = new Model({x:"1", y:[1,2,3]})
# z.on "change", console.log
z.x("w")
z.y("wow")
console.log z.getHistory()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment