summaryrefslogtreecommitdiff
path: root/js/codeq/stateMachine.js
blob: dff89d55a8bf74e22b96b58cc8bda11ee8a9237d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Created by robert on 9/15/15.
 */

codeq.makeStateMachine = function(def){
    var currState = null;
    return {
        'transition': function(name){
            var newState = def[name];
            if (!newState) {
                codeq.log.error('Cannot transition to state ' + name + ': it is not defined');
                return;
            }
            if (newState === currState) {
                codeq.log.info('Will not transition between identical states: ' + name);
                return;
            }
            if(currState !== null) currState.exit();
            currState = newState;
            currState.enter.apply(currState,Array.prototype.slice.apply(arguments,[1]));
        },
        'destroy': function(){
            if(currState !== null) currState.exit();
            currState = null;
        },
        'register': function(name,state){
            if (name in def) codeq.log.error('The state ' + name + ' is already registered, overriding');
            def[name] = state;
        }
    }
};
codeq.globalStateMachine = codeq.makeStateMachine({});