An Introduction To Flux

Posted on by Chris McLean

An Introduction To Flux

The JavaScript community likes to come up with new frameworks and patterns as frequent as it rains here in Orlando Florida. Flux is yet another addition to the JS pattern family. Facebook, the recent pushers of this style of development, build their applications this way with React. It’s verbose. It’s direct. It’s a pain to learn, but makes quite a bit of sense once you dig into it.

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.

  • js
    • collections
    • models
    • views
    • router.js
    • app.js

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.

Model

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.

let _alertModelUID = 0;
class AlertModel {
constructor(alert) {
this._uid = _alertModelUID;
this._message = alert.message || '';
this._from = alert.from || '';
this._priority = alert.priority || 0;
_alertModelUID++;
}
get priorityCode() {
if(this._priority > 9) {
return 'high';
}
else if(this._priority <= 9 && this._priority >= 5) {
return 'medium';
}
else {
return 'low';
}
}
get uid() {
return this._uid;
}
get message() {
return this._message;
}
set message(message) {
if(typeof message === 'string') {
this._message = message;
}
else {
throw new Error('Message is not a string value');
}
}
get from() {
return this._from;
}
set from(message) {
if(typeof from === 'string') {
this._from = from;
}
else {
throw new Error('From is not a string value');
}
}
get priority() {
return this._priority;
}
set priority(priority) {
if(typeof priority === 'number') {
this._priority = priority;
}
else {
throw new Error('priority is not a number value');
}
}
}
export default AlertModel;

Store

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.

import EventEmitter from 'events';
import AlertModel from '../models/alert';
class AlertStore extends EventEmitter {
constructor() {
super();
this._alerts = {};
setInterval(()=> {
this.add({message: 'Hello, I am a pretzle', from: 'Foo McBar', priority: (Math.random() * 10)});
}, 2000);
}
alerts() {
return this._alerts;
}
add(alertParams) {
let alert = new AlertModel(alertParams);
this._alerts[alert.uid] = alert;
this.emitChange();
}
emitChange() {
this.emit('alert-change');
}
addChangeListener(callback) {
this.on('alert-change', callback);
}
removeChangeListener(callback) {
this.removeListener('alert-change', callback);
}
}
export default new AlertStore();

Dispatcher

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.

import Flux from 'flux';
import AlertStore from '../stores/alert_store';
let AppDispatcher = new Flux.Dispatcher();
AppDispatcher.register((action) => {
switch(action.actionType) {
case 'ADD_ALERTS':
AlertStore.add(action.alert);
break;
default:
}
});
export default AppDispatcher;

Actions

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.

import AppDispatcher from '../dispatcher/app_dispatcher';
let AlertActions = {
addAlert: (message, from, priority) => {
AppDispatcher.dispatch({
actionType: 'ADD_ALERTS',
alert: { message: message, from: from, priority: priority }
});
}
};
export default AlertActions;
view raw flux-actions.js hosted with ❤ by GitHub

Components

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.

import React from 'react';
class Modal extends React.Component {
visibilityClass() {
return this.props.isOpen ? 'open' : 'closed';
}
render() {
return (
<div className={ 'modal -' + this.visibilityClass() }>
{this.props.children}
</div>
);
}
}
export default Modal;
view raw flux-modal.js hosted with ❤ by GitHub
import React from 'react';
class Alert extends React.Component {
constructor() {
super();
}
render() {
return (
<li>
<p>From: { this.props.alert.from }</p>
<p>Message: { this.props.alert.message }</p>
<p className={'priority -' + this.props.alert.priorityCode }>Priority { this.props.alert.priority }</p>
</li>
);
}
}
export default Alert;
view raw flux-alert.js hosted with ❤ by GitHub
import React from 'react';
import AlertStore from '../stores/alert_store';
import AlertActions from '../actions/alert_actions';
import Alert from '../components/alert';
import Modal from './modal';
class Alerts extends React.Component {
constructor() {
super();
let alerts = AlertStore.alerts();
this.state = { alerts: alerts, severity: this.severity(alerts), modalOpen: false };
AlertStore.addChangeListener(this.onChange.bind(this));
}
componentWillUnmount() {
AlertStore.removeChangeListener(this.onChange);
}
onChange() {
let alerts = AlertStore.alerts();
this.setState({
alerts: alerts,
severity: this.severity(alerts)
});
}
num(alerts) {
return Object.keys(alerts).length;
}
severity(alerts) {
let num = this.num(alerts);
if(num <= 5) {
return '';
}
else if(num <= 10) {
return '-warning';
}
else {
return '-failing';
}
}
toggleModal() {
this.setState({ modalOpen: !this.state.modalOpen });
}
alerts() {
return Object.keys(this.state.alerts).map((uid) => {
let alert = this.state.alerts[uid];
return (
<Alert key={alert.uid} alert={alert}/>
);
});
}
render() {
return (
<div>
<p onClick={this.toggleModal.bind(this)} className={'alert ' + this.state.severity}>
{ this.num(alerts); }
</p>
<Modal isOpen={this.state.modalOpen}>
<ul className='alert-list'>
{ this.alerts() }
</ul>
</Modal>
</div>
);
}
}
export default Alerts;
view raw flux-alerts.js hosted with ❤ by GitHub

Thoughts

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.