Flux é o padrão de arquitetura criado pelo Facebook para aplicações web frontend com fluxo de dados unidirecional.
Visão geral da arquitetura (Architecture Overview)
┌───────────────┐
│ Action Creator│ ───> Action ───┐
└───────────────┘ │
▼
┌───────┐ ┌────────────┐
│ View │ <── Change Event ─── │ Store │ <─── Dispatch(Action)
└───────┘ └────────────┘
│ ▲
└──────── Action Trigger ───────┘
- Dispatcher: Central hub receiving actions and broadcasting to registered callbacks.
- Stores: Maintain state and business logic, updating on action dispatch.
- Views: React components listening to store changes and triggering actions.
Dispatcher e sequenciamento com waitFor
const { Dispatcher } = require('flux');
const AppDispatcher = new Dispatcher();
// Register a store callback; returns a token used for waitFor()
const token = AppDispatcher.register(function (payload) {
switch (payload.actionType) {
case 'TODO_CREATE':
TodoStore.create(payload.text);
TodoStore.emitChange();
break;
}
});
// Broadcast action payload
AppDispatcher.dispatch({
actionType: 'TODO_CREATE',
text: 'Learn Flux'
});
// Sequencing with waitFor()
const FlightStore = {
dispatcherIndex: AppDispatcher.register(function (payload) {
switch (payload.actionType) {
case 'BUY_TICKET':
AppDispatcher.waitFor([CityStore.dispatcherIndex]);
FlightStore.country = CityStore.getCountry();
break;
}
})
};
Estrutura de Store e integração com componentes React
const EventEmitter = require('events').EventEmitter;
const TodoStore = Object.assign({}, EventEmitter.prototype, {
_todos: {},
getAll() { return this._todos; },
emitChange() { this.emit('change'); },
addChangeListener(cb) { this.on('change', cb); },
removeChangeListener(cb) { this.removeListener('change', cb); }
});
TodoStore.dispatchToken = AppDispatcher.register(function (action) {
switch (action.type) {
case 'TODO_CREATE':
TodoStore._todos[Date.now()] = { text: action.text };
TodoStore.emitChange();
break;
}
});