Passing variables in Machina.js

189 Views Asked by At

I'm trying to get to grips with the workings of machina.js.

I have definied state1 which does it's own thing, and it produces a variable someVar, and then it transitions to state2.

How can I pass someVar as an argument to state2?

var fsm = new machina.Fsm({
    initialState: "uninitialized",
    states: {
        uninitialized: {},
        state1: {
            _onEnter: function() {
                var someVar = "..."; // Stuff.
                this.transition("state2");
            }
        },
        state2: {
            _onEnter: function() {
                // someVar as argument somehow...?
                console.log(someVar);
            }
        }
    }
});
1

There are 1 best solutions below

0
On

You could probably do something like this:

function FiniteStateMachineSetup() {
    this.someVar = null;
    this.fsm = new machina.Fsm({
        initialState: "uninitialized",
        states: {
            uninitialized: {},
            state1: {
                _onEnter: state1_onEnter.bind(null, this)
            },
            state2: {
                _onEnter: state2_onEnter.bind(null, this)
            }
        }
    });
}

function state1_onEnter(self) {
    self.someVar = "..."; // Stuff.
    self.fsm.transition("state2");
}

function state2_onEnter(self) {
    // someVar as argument somehow...?
    console.log(self.someVar);
}

You'd then call the code by:

FiniteStateMachineSetup();