Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[question] How is it possible add different data for each state? #149

Open
menteora opened this issue Feb 1, 2018 · 3 comments
Open

[question] How is it possible add different data for each state? #149

menteora opened this issue Feb 1, 2018 · 3 comments

Comments

@menteora
Copy link

menteora commented Feb 1, 2018

I took your guide that speak about single data shared from all states or passed on initialization, but I don't understand how to define one color for each state, for example.

Thanks You

Guide Reference: http://github.com/jakesgordon/javascript-state-machine/blob/master/docs/data-and-methods.md

@miniatureape
Copy link

miniatureape commented Feb 25, 2018

I don't think there is a library supported method, but I've done:

let machine = StateMachine({
   ... state setup ...
    data: {
        firstState: {a: 1}, 
        secondState: {}
    },
    methods: {
        onFirstState: function(lifecycle) {
             // logs {a: 1}
             console.log(this[lifecycle.to]);
        }
    }
})

@rickbsgu
Copy link

rickbsgu commented Feb 25, 2018

Try using a function -

data: function() { return {
  firstState: { a: 1},
  secondState: {}
}};

@rainbow-bamboo
Copy link

rainbow-bamboo commented Nov 21, 2024

2024, but another approach is:

// Define your data as an array of objects with a name field that corresponds to its state name
const waterCycle = [{name: "water", color: "blue", temperature: 30}, 
                    {name: "ice", color: "white", temperature: -10 }]

const machine = new StateMachine({
        init: initState,
        transitions: transitions,

        // Assign the data on the machine to be that array
        data: { waterCycle },

        // Add a method to access the data based on the current state
        methods: {
            activeCycleData: function () {
                return this.data.find((c) => c.name == this.state);
            }
        }
    })

Then to get the color of the active state you would call:

machine.activeCycleData().color

Or its temperature:

machine.activeCycleData().temperture


Related

You can call transitions based on it's name by using the syntax:

machine["transition name"]()

In addition to the

machine.transitionName()

form from the docs. This is helpful in the case where the transition names are only available at runtime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants