matthewp / robot

🤖 A functional, immutable Finite State Machine library

Home Page:https://thisrobot.life

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Usage with vanilla javascript

ivandotv opened this issue · comments

I see there are integrations with popular libraries. However, can this be used with vanilla js?
Is there a callback where can respond to transitions and state
Something like this (from xstate):

// Interpret the machine
const service = interpret(machine);

// Add a state listener, which is called whenever a state transition occurs.
service.onTransition(state => {
  console.log(state.value);
});

A state transition can do work. Let's say, you want to change a class on a button.
The button would have an on click event handler which would send('clicked', refToButtonElement) to the machine.
Your machine would than be coded to set the class of the button element on transition.

You can even code your machine to get data (rest calls) on transition. It's all in docs, and there are some really good examples... and they are mostly in plain, vanilla, javascript.

The integrations are just icing. In most frameworks it's preferred to pass state changes as props, to your objects, to react to. The integrations just provide a mechanism to help that happen in a way that makes sense for the specific framework. Robot doesn't place any limits on what you can do with a machine, some frameworks, recommend you do things a particular way, and integrations help you target your machines actions to the framework, they aren't necessary at all, but damn useful nonetheless.

Hmm, continuing with your example, I don't want the machine to have access to the button.
I want to change the button class in response to some state/context change in the machine.
Machine needs to be decoupled from the DOM.

Oh, when I was looking at the documentation, I completely missed the onChange param in the interpret function.
Thanks