[XState] Create Actor in Vanilla Javascript

 

function countBehavior(state, event) {
  if (event.type === "INC") {
    return {
      ...state,
      count: state.count + 1
    }
  }
}

function createActor(behavior, initialState) {
  let currentState = initialState
  const listeners = new Set()
  return {
    send: (event) => {
      currentState = behavior(currentState, event)
      listeners.forEach(listener => {
        listener(currentState)
      })
    },
    subscribe: (listener) => {
      listeners.add(listener)
      listener(currentState)
    },
    getSnapshot: () => {
      return currentState
    }
  }
}

const actor = createActor(countBehavior, {count: 12})
actor.subscribe(console.log)

 

posted @ 2022-11-30 01:35  Zhentiw  阅读(28)  评论(0编辑  收藏  举报