首页 > 代码库 > [整理]JS中的状态机
[整理]JS中的状态机
/*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/
[整理]JS中的状态机
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。