I want to create an event system. Components should be able to listen to various events inside the app and respond accordingly. What's the best way to implement this?
I believe that the Flux architecture was designed to make everything a one-way flow. In the video explaining Flux (at this specific moment: youtu.be/nYkdrAPrdcw) an engineer shows that an application that uses Flux removes all of the complex communication between views and controllers. An global event system would bring back all of the problems that Flux is trying to prevent I believe.
I have had slight experience with Alt, a Flux compliant library which is great to use. It might provide some of the functionality you're looking for. alt.js.org
Note: I don't know a whole lot about React, I'm still learning myself.
Sandeep Panda
co-founder, Hashnode
Well, React promotes unidirectional data flow from parent to child. But there are many cases where you will need a global event system. For example, some of your components might want to listen to a path change event and react to it. Here is how you can do it.
P.S. I am using Alt, a Flux implementation.
First you need to create a store. Let's call it
EventStore:Now you need to create some actions. Let's create a file called
EventActions:Now whenever you need to trigger a particular event you just have to call
EventActions.triggerEvent('sample.event').In order to listen to this event your component just needs to do the following in
componentDidMountcallback.Inside the callback
onEventReceivedyou can use a simple switch case to put a check on the event type and respond accordingly.Let me know if you have any questions!