@@ -16,7 +16,7 @@ StateMachine = {
1616 var from = ( e . from instanceof Array ) ? e . from : [ e . from ] ;
1717 events [ e . name ] = events [ e . name ] || { } ;
1818 for ( var n = 0 ; n < from . length ; n ++ )
19- events [ e . name ] [ from [ n ] ] = e . to ;
19+ events [ e . name ] [ from [ n ] ] = e ;
2020 }
2121
2222 if ( initial ) {
@@ -47,39 +47,66 @@ StateMachine = {
4747
4848 buildEvent : function ( name , map ) {
4949
50+ var beforeEvent = function ( name , args ) {
51+ var func = this [ 'onbefore' + name ] ;
52+ if ( func && ( false === func . apply ( this , args ) ) )
53+ return false ;
54+ } ;
55+
56+ var exitState = function ( from , args ) {
57+ var func = this [ 'onleave' + from ] ;
58+ if ( func )
59+ func . apply ( this , args ) ;
60+ } ;
61+
62+ var enterState = function ( to , args ) {
63+ var func = this [ 'onenter' + to ] || this [ 'on' + to ] ;
64+ if ( func )
65+ func . apply ( this , args ) ;
66+ } ;
67+
68+ var changeState = function ( from , to , args ) {
69+ var func = this [ 'onchangestate' ] ;
70+ if ( func )
71+ func . call ( this , from , to ) ;
72+ } ;
73+
74+ var afterEvent = function ( name , args ) {
75+ var func = this [ 'onafter' + name ] || this [ 'on' + name ] ;
76+ if ( func )
77+ func . apply ( this , args ) ;
78+ } ;
79+
80+ var transition = function ( from , to , args ) {
81+ this . current = to ;
82+ enterState . call ( this , to , args ) ;
83+ changeState . call ( this , from , to ) ;
84+ } ;
85+
5086 return function ( ) {
5187
5288 if ( this . cannot ( name ) )
5389 throw "event " + name + " innapropriate in current state " + this . current ;
5490
55- var from = this . current ;
56- var to = map [ from ] ;
91+ var from = this . current ;
92+ var to = map [ from ] . to ;
93+ var async = map [ from ] . async ;
5794
58- var beforeEvent = this [ 'onbefore' + name ] ;
59- if ( beforeEvent && ( false === beforeEvent . apply ( this , arguments ) ) )
95+ if ( beforeEvent . call ( this , name ) === false )
6096 return ;
6197
6298 if ( this . current != to ) {
6399
64- var exitState = this [ 'onleave' + this . current ] ;
65- if ( exitState )
66- exitState . apply ( this , arguments ) ;
67-
68- this . current = to ;
69-
70- var enterState = this [ 'onenter' + to ] || this [ 'on' + to ] ;
71- if ( enterState )
72- enterState . apply ( this , arguments ) ;
100+ var self = this ;
101+ this . transition = function ( ) { transition . call ( self , from , to , arguments ) ; self . transition = null ; } ;
73102
74- var changeState = this [ 'onchangestate' ] ;
75- if ( changeState )
76- changeState . call ( this , from , to ) ;
103+ exitState . call ( this , this . current , arguments ) ;
77104
105+ if ( ! async )
106+ this . transition ( ) ;
78107 }
79108
80- var afterEvent = this [ 'onafter' + name ] || this [ 'on' + name ] ;
81- if ( afterEvent )
82- afterEvent . apply ( this , arguments ) ;
109+ afterEvent . call ( this , name , arguments ) ;
83110 }
84111
85112 }
0 commit comments