Dive into Flux

Hi JavaScript soldiers,

let me share some opinions about the Flux application architecture. Before we begin, let’s take a look at the two-way data binding features. It sounds interesting and promises you easy development. It even does so.
Until your app is big enough.

Once you need to look under the hood of how it works, it’s really hard to understand the data flow, all the points where data could be changed and the sequence of these changes. There is simpler way of data management using one-direction data flow.

The State

Well, there must be kind of data storage in your application. I don’t mean the SQL database on the server. I mean kind of object with the tenant data that are used by your app on the front-end. These data either are shown now or will be shown by some conditions.

Not the whole data bunch will be shown in one moment. There is the part related to current visuals, let’s say the State.

<nerd-mode> Technically the State contains not only the part of data related to visuals. It’s like the snapshot of the system.
So if we have the whole data bunch and apply the “State X”, the system should become like it was by “X”. </nerd-mode>

From now on if I say Store I mean the data storage in general and the State in particular.

One direction

As you already understand, the Store/State resembles the Model in MVC. The View becomes the data from the Store/State.
So S → V.
Consider that the data enter the Store via one single gate, let’s say Action. Taking into accounting previous formula, A → S → V.
Even if the View wants to update the Store, it does not do it directly:
wrong: S ← V
right: V → A → S

Continuing this, there might be different sources of data updates but all they go via Actions:

  • XHR → Actionxhr → Store
  • View one → Actionv1 → Store
  • View two → Actionv2 → Store
  • setTimeout() → Actiontimer → Store

and so on.

Wait, the app must be asynchronous!

Right, we do not know how and when the Data/State changes. A way of handling state changes well is event mechanism:
the Store emits the event and the View listens to it.
That’s clear but what inside the A-S– or xxx-A-S-cycle? — The principle is pretty similar:
the Action emits the event and the Store listens to it.

There is one moment here. Flux architects from the Facebook designed the Dispatcher as the event engine. So here is the scheme:

// ------------ actions.js ------------
var Actions = {
  update: function (data) {
    // emit the event
    Dispatcher.dispatch({
      type: 'UPDATE',
      payload: data
    });
  }
}


// ------------ store.js ------------
var _store = { data: null };

// inheriting from NodeJS EventEmitter
var Store = assign({}, EventEmitter.prototype);

// listen to what Actions emit
Dispatcher.register(function (action) {
  if (action.type === 'UPDATE') {
    _store.data = data;
    Store.emit('CHANGE', _store);
  }
});


// ------------ view.js ------------
Store.addEventListener('CHANGE', function (data) {
  document.querySelector('#field').innerHTML = data || '';
});

Ok, what benefits do I get?

  1. Any piece of code that wants to change the data should use Actions.update(...). That’s great: we have single entry point for all the data in the app!
  2. This code supports asyncronous approach well. Considering you have to get new data by XHR, you just invoke the
    Actions.update(JSON.parse(xhr.responseText));
    inside the xhr.onreadystatechange handler!
    The data will be updated automatically once they appear.
  3. This approach supports multiple data sources:
    document.querySelector('#name').onchange = function () { Actions.update(this.value); };
  4. This approach supports different strategies for different data sources, for instance,
    • you can design different Actions for XHR data and for Form data,
    • assign ’em different types,
    • manage ’em in different way inside store.js → Dispatcher.register()
    • and even decide whether the Store should emit the CHANGE event or not depending on data source/strategy.

Now the most interesting bonus: you can handle the asyncronous code as sync one!
How is it made? Wait for the next episode.


Experienced professionals can detect lack of nuances like dispatchToken and so on. I described how Flux works roughly; more info could be found on their site.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s