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.
Stateful DOM wrapper
// 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment