Closed WoodyDark closed 3 years ago
Absolutely, as you might know Typescript it turns into Javascript when transpiled. I do strongly recommend to use Typescript if you can as you will get several advantages related to the data type and so, but if you can't I leave here the example of the readme without typescript.
/// traffic-light.machine.ts
import { assign } from 'xstate/lib/actions';
// Initial context used in the xStateInit() method
export const TrafficLightInitialContext = {
carCount: 0,
finedPlates: [],
};
// Possible states of the machine
export const TrafficLightStates = {
RED: 'RED',
AMBER: 'AMBER',
GREEN: 'GREEN',
}
// Possible actions of the whole machine
export const TrafficLightActions = {
GO_GREEN: 'GO_GREEN',
GO_AMBER: 'GO_AMBER',
GO_RED: 'GO_RED',
COUNT_CAR: 'COUNT_CAR',
FINE_CAR: 'FINE_CAR',
}
// Definition of the state machine
export const TrafficLightMachineConfig = {
initial: TrafficLightStates.RED,
states: {
[TrafficLightStates.RED]: {
on: {
[TrafficLightActions.GO_GREEN]: {
target: TrafficLightStates.GREEN,
},
[TrafficLightActions.FINE_CAR]: {
actions: assign((ctx, event) => ({
finedPlates: [...ctx.finedPlates, event.plate],
})),
},
},
},
[TrafficLightStates.AMBER]: {
on: {
[TrafficLightActions.GO_RED]: {
target: TrafficLightStates.RED,
},
},
},
[TrafficLightStates.GREEN]: {
on: {
[TrafficLightActions.GO_AMBER]: {
target: TrafficLightStates.AMBER,
},
[TrafficLightActions.COUNT_CAR]: {
actions: assign((ctx, event) => ({
carCount: ctx.carCount + 1,
})),
},
},
},
},
};
And the component:
import { Component, Vue } from 'vue-property-decorator';
import { StateMachine } from 'vue-xstate';
import {
TrafficLightInitialContext,
TrafficLightMachineConfig,
} from './TrafficLight.machine.ts';
@Component
class TrafficLight extends Vue {
// Your class definition
readonly machine = new StateMachine(
TrafficLightInitialContext,
TrafficLightMachineConfig,
);
}
Hope it helps!
Thank you! That's very helpful
Is there a way to use this with Javascript instead of Typescript and if yes, is there an example of how to do so?