码迷,mamicode.com
首页 > 系统相关 > 详细

[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine

时间:2020-01-21 17:51:17      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:rop   OLE   function   log   init   arguments   options   prope   can   

We can invoke a callback as a service when we enter a state in XState. This gives us the ability to trigger various functionality by responding to events sent to the service, and allows us to send events back to the parent machine.

We do this by writing a "callback handler" and setting it as the src of our invoked service. A callback handler is a function that receives the current context and the event object that triggered the invocation. This function returns another function that receives two functions as arguments. A callback function to send events to the parent machine, and an onEvent function for the handler to respond to events sent to the handler.

The way events are sent to the callback handler is by utilizing the options argument of the send action creator. We identify where we send events to using the to property, and setting the value to the id of our service.

 

const handlerEchoCallback = (context, event) => {
  return (callback, onReceive) => {
    onReceive(e => {
      if (e.type === FOO) {
       callback(ECHO); // call the ‘ECHO‘ action
      }
    })
  }
}

const callbackMachine = Machine({
  id: callbackMachine,
  initial: listening,
  states: {
    listening: {
      invoke: {
        src: handlerEchoCallback,
        id: handlerEchoCallback
      },
      on: {
        SPEAK: {
          actions: send(FOO, {
            to: handlerEchoCallback
          })
        },
        ECHO: {
          actions: (context, event) => {
            console.log(echo, context, event);
          }
        }
      }
    }
  }
})

 

[XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine

标签:rop   OLE   function   log   init   arguments   options   prope   can   

原文地址:https://www.cnblogs.com/Answer1215/p/12222589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!