Skip to content

Instantly share code, notes, and snippets.

@davidhellsing
Created June 23, 2014 21:51
Show Gist options
  • Save davidhellsing/8d310b36a9825f318b13 to your computer and use it in GitHub Desktop.
Save davidhellsing/8d310b36a9825f318b13 to your computer and use it in GitHub Desktop.

Revisions

  1. davidhellsing created this gist Jun 23, 2014.
    44 changes: 44 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    // example:
    // var stateHandler = State(node, function(state) { this.className = state.active ? 'active' : '' })
    // stateHandler.set({ active: true })

    var states = {}
    function State(elem, render) {
    if ( states.hasOwnProperty(elem) )
    return states[elem]
    if ( !(this instanceof State) ) {
    var instance = new State(elem, render)
    states[elem] = instance
    return instance
    }
    this.elem = elem
    this.state = {}
    this.render = function() {
    typeof render == 'function' && render.call(this.elem, this.state)
    }
    }

    State.prototype.get = function(key) {
    if ( key in this.state )
    return this.state[key]
    return null
    }

    State.prototype.set = function(obj) {
    var hasChanged = false
    for ( var i in obj ) {
    if( !this.state[i] || JSON.stringify(obj[i]) !== JSON.stringify(this.state[i]) )
    hasChanged = true
    this.state[i] = obj[i]
    }
    hasChanged && this.render()
    return this
    }

    State.prototype.destroy = function() {
    this.state = {}
    this.render()
    if( states.hasOwnProperty(this.elem) )
    delete states[this.elem]
    return this
    }