forked from jakesgordon/javascript-state-machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state-machine.min.js
1 lines (1 loc) · 1.93 KB
/
state-machine.min.js
1
StateMachine={VERSION:"2.0.0",create:function(e,f){var h=(typeof e.initial=="string")?{state:e.initial}:e.initial;var d=f||e.target||{};var j=e.events||[];var g=e.callbacks||{};var b={};var i=function(k){var m=(k.from instanceof Array)?k.from:[k.from];b[k.name]=b[k.name]||{};for(var l=0;l<m.length;l++){b[k.name][m[l]]=k.to}};if(h){h.event=h.event||"startup";i({name:h.event,from:"none",to:h.state})}for(var c=0;c<j.length;c++){i(j[c])}for(var a in b){if(b.hasOwnProperty(a)){d[a]=StateMachine.buildEvent(a,b[a])}}for(var a in g){if(g.hasOwnProperty(a)){d[a]=g[a]}}d.current="none";d.is=function(k){return this.current==k};d.can=function(k){return !!b[k][this.current]&&!this.transition};d.cannot=function(k){return !this.can(k)};if(h&&!h.defer){d[h.event]()}return d},beforeEvent:function(b,e,d,a){var c=this["onbefore"+b];if(c){return c.apply(this,[b,e,d].concat(a))}},afterEvent:function(b,e,d,a){var c=this["onafter"+b]||this["on"+b];if(c){return c.apply(this,[b,e,d].concat(a))}},leaveState:function(b,e,d,a){var c=this["onleave"+e];if(c){return c.apply(this,[b,e,d].concat(a))}},enterState:function(b,e,d,a){var c=this["onenter"+d]||this["on"+d];if(c){return c.apply(this,[b,e,d].concat(a))}},changeState:function(b,e,d,a){var c=this["onchangestate"];if(c){return c.apply(this,[b,e,d].concat(a))}},buildEvent:function(a,b){return function(){if(this.transition){throw"event "+a+" innapropriate because previous transition did not complete"}if(this.cannot(a)){throw"event "+a+" innapropriate in current state "+this.current}var f=this.current;var e=b[f];var d=Array.prototype.slice.call(arguments);if(this.current!=e){if(false===StateMachine.beforeEvent.call(this,a,f,e,d)){return}var c=this;this.transition=function(){c.transition=null;c.current=e;StateMachine.enterState.call(c,a,f,e,d);StateMachine.changeState.call(c,a,f,e,d);StateMachine.afterEvent.call(c,a,f,e,d)};if(false!==StateMachine.leaveState.call(this,a,f,e,d)){if(this.transition){this.transition()}}}}}};