Created
June 23, 2014 21:51
-
-
Save davidhellsing/8d310b36a9825f318b13 to your computer and use it in GitHub Desktop.
Revisions
-
davidhellsing created this gist
Jun 23, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 }