An Introduction To Flux
Here it is straight. Flux architecture requires a few parts.
- Dispatcher : A promise queue. Tells a store to update when a component does something.
- Action Helpers : Helper methods that your components use for calling the dispatcher.
- Stores : An object that holds a bunch of things and broadcasts an event when it changes.
- Components : Your view controllers, probably in React
These components create a pattern where data moves in a circle and all views/subviews react directly to changes in data.
This should start to look familiar to you because it’s exactly how Backbone.js works, but without public facing actions or a dispatcher.
When you realize that stores are just collections and that components are just views, things start to make a bit of sense.
If you’ve also played around with broadcasts in Angular, this will look familiar as well.
Let’s Build a Basic Alert System
Dependencies - react - react-dom - events - flux
This will probably deviate from most examples. I’ve forgone using constants for action names and added a model layer. I also moved storage registration logic to the dispatcher file. This is really logic for the dispatcher anyway, not the store.
We start with a todo model. This is where validations, id management, and business logic will probably occur. I know it’s not part of the Flux way of doing things, but they’re nice to have. Any model library will probably work here. I just chose to build one myself as to not add to the noise.
Stores are our data controllers. They manage a collection of things, how to interact with them, and broadcast events when change occurs. We extend EventEmitter to grab hold of all the event broadcasting goodness built in.
The dispatcher is our promise queue. Everytime an action is called, it gets resolved in the dispatcher and then goes off to tell the store to do something. Maybe it adds a new todo, or clears them all.
Actions are our helper methods for working with the dispatcher. You may have several components that make use of the same actions, so we stick them here for common use. You could hypothetically use the dispatcher directly though, should you wish. I find it helpful to at least define how data packets are structured here.
Components are your views and can be made up other cusome components. Think Backbone views, Angular Directives, etc. This is using React in ES6.
The following components build a notification icon that changes colors as more alerts are added. When you click on the icon, it brings up a modal window detailing individual alert messages.
Flux is more verbose and has more boilerplate than traditional MVC, but it is a lot more direct in how it handles the relationship between your components and application data. I find it much easier to maintain apps dependent on application wide state in this pattern, but less so for proof on concept apps, or smaller scale MVPs.