fluxxor
fluxxor copied to clipboard
Store Helper to bind namespaced actions and organize methods
I wrote a Store mixin for my application and was curious if other people had similar issues and were interested in a PR.
I have a Store in my application with a very large number actions to bind to, so my initialize method originally looking something like this.
this.bindActions(
constants.widgets.new.pending, this.onWidgetNewPending,
constants.widgets.new.success, this.onWidgetNewSuccess,
constants.widgets.new.error, this.onWidgetNewError,
constants.widgets.update.pending, this.onWidgetUpdatePending
// The pattern continues for a while... );
This worked fine, but bothered me for a few reasons
- The code is more verbose the needed, considering it all follows a similar pattern, and the actions are already described in the constants
- By the time I repeated this a few times, the store was hundreds of line of code with no organization enforced.
To address this, I wrote a utility function autoBindActions
which takes in an object of high level namspaces as keys, and an array of lower level namespaces as the value.
It roughly does something like this:
- Binds the store to all actions defined in the Flux constants under the provided namespaces
- When the Store receives one of these actions from autoBindActions, it checks if the Store has a handler defined for the higher level namespace (ie
widgets
), and checks for an appropriate function in that handler if so, using a pattern likeonNewPending()
. This allows me to logically organize the functions of my Store into separate objects. If a handler doesn't exist, it checks for the appropriate function in the Store, and if that function exists calls a generic function to handle this action (ieonPending()
)
The store now looks like this
this.autoBindActions({
widgets: ['new', 'update', 'delete'],
categories: ['load', 'subCats', 'scripts']});
// further down in the store, I setup the handlers
categoriesHandler: App.Flux.StoreHandlers.Category,
widgetsHandler: App.Flux.StoreHandlers.Widget
Right now this code is a mixin slightly customized for my needs and in CoffeScript, so I wanted to gauge interest before I rewrote it in legible JS, etc. Obviously the details can be changed / debated once I put in the PR.