[整理]JS中的状态机

时间:2021-10-27 09:01:25
/*StateMachine*/
var StateMachine = (function(){ function StateMachine(opts){
this.current = opts.initial||'none'
this.events = opts.events||[] for(var i=0,length=this.events.length;i<length;i++){
var self = this
var evt = self.events[i] self[evt.name] = function (self,evt){
return function(){ if(typeof self.onchanging === 'function'){
self.onchanging(evt)
console.log('trace->onchanging')
} if(self.is(evt.from)){
self.current = evt.to if(typeof self.onchanged === 'function'){
self.onchanged()
console.log('trace->onchanged')
} console.log(evt.name+'->transition from '+evt.from+' to '+evt.to)
}
}
}(self,evt)
}
} StateMachine.prototype = {
is: function (s){
return this.current===s
},
can: function (e){
var _events = this.events
var _event for(var i=0,length=_events.length;i<length;i++){
_event = _events[i] if(_event.from===this.current&&_event.name===e){
return true
}
} return false
}
} return {
create: function (opts){
var fsm = new StateMachine(opts)
return fsm
}
}
})()

参考

http://www.ruanyifeng.com/blog/2013/09/finite-state_machine_for_javascript.html
http://www.cnblogs.com/wadeyu/archive/2012/11/23/2784894.html
http://developer.51cto.com/art/201405/440102.htm
http://segmentfault.com/q/1010000000673177
https://github.com/jakesgordon/javascript-state-machine/