Overview In Code
Store
Essentially the store is just an object. All the defaults known up front for the application should be provided to the store object before being passed to the FauxFlux instance.
var store = {
newTodoText: '',
todos: [{
id: 1,
title: 'Learn FauxFlux',
completed: false
}]
};
Actions
Actions are an array of objects that contain two properties - name
and action
. The name
property is the descriptor for that particular action. the action
property is the function that gets called from the dispatcher from some sort of interaction (usually from a user interaction initiated in the view).
The action
gets passed two arguments. The first being the FauxFlux instance (store, dispatcher, mobx, etc...) and the second being the payload that was passed to the dispatcher.
var actions = [
{
name: 'updateNewTodoText',
action: function (ff, payload) {
ff.store.newTodoText = payload;
}
},
{
name: 'editTodoText',
action: function (ff, payload) {
var index = payload.index;
var title = payload.newTitle;
ff.store.todos[index].title = title;
}
}
];
Creating the Instance
The store and the actions, as well as any additional options, are then passed to FauxFlux to create the instance.
var ff = new FauxFlux(store, actions [, options]);
Views
FauxFlux isn't opinionated about the view layer. There are a number of great view libraries that work well with this pattern. React, Preact, and basically any of the Virtual DOM libraries that exist could be a good fit. But this can also work with just plain old JS. (Doing this in plain JS is not going to be performant for large application though, but it can be done!)
// Bootstrap our view
var appContainer = document.getElementById('app');
// Create a reaction to updates in `ff.store`.
ff.autorun(function () {
var store = ff.store;
var todosContainer = document.createElement('ul');
store.todos.forEach(function (todo, index) {
var todosItem = document.createElement('li');
todosItem.onclick = function () {
ff.dispatch('editTodoText', {
index: index,
newTitle: 'Yeah, you just clicked me!'
});
};
todosContainer.appendChild(todosItem);
});
appContainer.innerHTML = '';
appContainer.appendChild(todosContainer);
});