Created
October 13, 2013 20:59
-
-
Save GingerBear/6967374 to your computer and use it in GitHub Desktop.
JavaScript State Machine
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
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