Skip to content

Instantly share code, notes, and snippets.

@GingerBear
Created October 13, 2013 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GingerBear/6967374 to your computer and use it in GitHub Desktop.
Save GingerBear/6967374 to your computer and use it in GitHub Desktop.
JavaScript State Machine
var Events = {
bind: function(){
if (!this.o) this.o = $({});
this.o.bind.apply(this.o, arguments);
},
trigger: function(){
if (!this.o) this.o = $({});
this.o.trigger.apply(this.o, arguments);
}
};
var StateMachine = function(){};
StateMachine.fn = StateMachine.prototype;
$.extend(StateMachine.fn, Events);
StateMachine.fn.add = function(controller) {
this.bind('change', function(e, current){
if (controller == current) {
controller.activate();
} else {
controller.deactivate();
}
});
controller.active = $.proxy(function(){
this.trigger('change', controller);
}, this);
};
var con1 = {
activate: function() {
$('#d1').addClass('active');
},
deactivate: function() {
$('#d1').removeClass('active');
}
};
var con2 = {
activate: function() {
$('#d2').addClass('active');
},
deactivate: function() {
$('#d2').removeClass('active');
}
};
var sm = new StateMachine;
sm.add(con1);
sm.add(con2);
con1.active();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment