React.js - flux vs global event bus

前端 未结 4 1711
情书的邮戳
情书的邮戳 2021-02-15 01:45

What is the advantage of using Flux over a global event bus? I think the dispatcher is all that is needed:

  1. component publishes \'user event\' with data to the dis
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-15 02:13

    I believe it's all about code structure which is understandable even in large scale.

    Supose you have appState which holds underlying data for components.

    The components call action. Action is responsible for gather data from XHR or modify the incoming data from component and then it dispatch complete data to subscribed store.

    Store is the only part of your code, which can modify your appState and it is basically the only thing, what it does. It takes data from action and store them to appState or removes some data from appState according to action.

    Then you fire stateChanged event, which your component should listen to and will rerender.

    So you have all action specific logic in actions. You handle appState only in stores. And that should help you keep your code understandable.

    Flux pattern

    My understanding of why is good idea to dispatch only complete data comes mainly from this article. And it is based on official Facebook Flux diagram

    Flux architectire diagram

    The advantages of this approach are:

    • stores are simple and synchronous, does not contain decision logic, just handles given data
    • there is no need to fire another action in store, which will break one-directional chain of Flux
    • dispatcher is the single channel for all state changes, it knows what action with what data is processed, so its easier for debugging

提交回复
热议问题