tl;dr — A thin wrapper around Backbone Model and Collection to force uni-directional data flow for Flux architecture.

github.com/vidoss/flux-backbone

Ever since I learned about Facebook Flux, I was intrigued. The problem it is trying to solve resonated well with me. But most of the apps I work on day-to-day basis are Backbone apps. Since Flux is more of a pattern than a framework I ventured into changing my Backbone apps to use the Flux pattern.

My first approach to embrace the Flux’s philosophy of uni-directional data flow is to just use code conventions. Basically don’t write any code in View that will mutate the Model or Collections. As more people joined the project, I realized quickly it is not going to work. Even caught myself changing models from View.

What I needed was Backbone Models and Collection to throw exception when set from View or anywhere else for that matter. The only place models and collection can be changed are when they are inside the “dispatcher callback”. See below flux flow diagram for reference.

ref: image from flux Github page github.com/facebook/flux

This is what I want:

In Views and everywhere else…

var MyView = Backbone.View.extend({

...

onActionClicked: function() {

...

this.model.set({value: changedValue}); // Throw exception

...

}

...

});

Inside dispatch callback

var MyModel = FluxBackbone.Model.extend({

...

dispatchCallback: function(action) {

var data = action.data;

this.set(data); // Do not throw exception

...

}

});

The solution:

Wraps all the methods that mutates Models and Collection and throws exception unless called from inside dispatchCallback.

“dispatchCallback” is a special function that you override when extending FluxBackbone.Model or FluxBackbone.Collection. It also takes AppDispatcher as one of the options. Or you can call setDispatcher() explicitly to register for action events from the dispatcher.

var Dispatcher = require(‘flux’).Dispatcher;

var FluxBackbone = require('flux-backbone'); var AppDispatcher = new Dispatch(); var model = new FluxBackbone.Model({}, {

dispatcher: AppDispatcher

});

/* --- or --

model.setDispatcher(AppDispatcher);

*/

See the example TODO app for usage details:

https://github.com/vidoss/flux-backbone/tree/master/examples/todos