Backbone Dispatcher
Extension for using Flux architecture with Backbone instead of ReactJS.
╔════════════╗ ╔════════════════════╗ ╔═══════╗
║ Dispatcher ║──────>║ Models/Collections ║──────>║ Views ║
╚════════════╝ ╚════════════════════╝ ╚═══════╝
^ │
└────────────────────────────────────────────────┘
Installing
Via npm
npm install backbone-dispatcher --save
or via Bower
bower install backbone-dispatcher --save
Usage
var dispatcher = actions: 'ACTION_1' ; // It can also be a Collection var MyModel = ; var myModel = ; // When ACTION_1 is dispatched, pass the payload for myModel.methodName() // If doesn't pass the third argument, it will call myModel.ACTION_1() dispatcher; // You can dispatch like this dispatcher; dispatcher; // Now you can make your views listen to your store (Model or Collection)
API
extend([options])
: Static method, let's you extend the Dispatcher (check the examples below).createAction(actionName/actionObject[, beforeEmit/actionCallbacks])
: Instance method, creates a new action. Callbacks:shouldEmit(payload)
: Returns true if should emit, and false if not.beforeEmit(payload, next)
: Run right aftershouldEmit
, pass the changed payload as parameter to next.
createActions(arrayOfActions)
: Instance method, receive an array of methods that are passed tocreateAction()
.dispatch(actionName, payload)
: Instance method, dispatches an action.<actionName>(payload)
: Instance method, dispatches the action 'actionName'.register(actionName, model/collection[, callback])
: Makes the model/collections listen toactionName
, and will call eithercallback(payload)
(if callback is a function), ormodel[callback](payload)
/collection[callback](payload)
(if callback is a string corresponding to a model/collection's method name) when dispatched. Ifcallback
is not passed, it will be the same asactionName
(so amodel[actionName](payload)
would be executed).registerStore(actionNamesArray, model/collection[, callbacks])
: Callsregister
(see the line above) for each pair action/callback.callbacks
can also be a string or a function: in this case, all the actions will be bound to such unique callback.
Examples
var MyDispatcher = BackboneDispatcher; // You can create actions in the constructor var dispatcher = actions: 'action_1' name: 'action_2' { console; ; } { ifpayload < 2 console; return false; console; return true; } ; // Or like this dispatcher; // Or like this dispatcher; // Or like this dispatcher; // Or like this dispatcher; var MyCollection = ; var MyModel = ; var myModel = ; var myCollection = ; dispatcher; dispatcher; dispatcher; dispatcher; dispatcher; dispatcher;