Created
March 23, 2015 15:26
-
-
Save TannerRogalsky/f30d9f0bf599f16d586b to your computer and use it in GitHub Desktop.
Javascript Stateful
This file contains 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 characters
Stateful = { | |
extend: function(klass) { | |
var currentState = klass.prototype; | |
var states = {null: currentState}; | |
klass.prototype.gotoState = function(stateName, ...args) { | |
currentState = states[stateName]; | |
} | |
klass.addState = function(stateName, state) { | |
states[stateName] = state; | |
} | |
return new Proxy(klass, { | |
construct: function(target, args) { | |
var instance = Reflect.construct(target, args); | |
return new Proxy(instance, { | |
get: function(target, name, receiver) { | |
if (currentState[name]) { | |
return currentState[name]; | |
} else { | |
return target[name]; | |
} | |
} | |
}); | |
} | |
}); | |
} | |
} | |
function Test(foo) { | |
this.foo = foo; | |
this.test = 1; | |
} | |
var states = {}; | |
var currentState = Object.assign({}, Test.prototype); | |
Test.prototype.gotoState = function(stateName, ...args) { | |
currentState = states[stateName]; | |
} | |
Test.addState = function(stateName, state) { | |
states[stateName] = state; | |
} | |
Test.addState("TestState", { | |
foo: 'test state bar' | |
}) | |
t = new Test("bar"); | |
p = new Proxy(t, { | |
get: function(target, name, receiver) { | |
if (currentState[name]) { | |
return currentState[name]; | |
} else { | |
return target[name]; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment