Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Created March 23, 2015 15:26
Show Gist options
  • Save TannerRogalsky/f30d9f0bf599f16d586b to your computer and use it in GitHub Desktop.
Save TannerRogalsky/f30d9f0bf599f16d586b to your computer and use it in GitHub Desktop.
Javascript Stateful
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