[整理]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/

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。