Created
June 26, 2015 13:39
-
-
Save patio11/b472ccb2df3e1fcce78c to your computer and use it in GitHub Desktop.
Got tired of all the boilerplate with hooking up Stores/Actions so...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// When I was working on our React/Flummox app I got to the point where, per the docs, I had ~100 lines of code | |
// which were substantially predictable boilerplate, so I used some JS metaprogramming to condense them by 80%. | |
// Flummox docs: http://acdlite.github.io/flummox | |
// I use underscore.js below for utility but you can also just do a for loop. | |
class AppFlux extends Flux { | |
constructor() { | |
super(); | |
/* assuming action names like getFoo or verbNoun, Actions classes with names corresponding to Store classes, | |
and Store handler functions named handleGetFoo or handleVerbNoun, we can automatically skip a lot of the | |
boilerplate of wiring together this and instead spend more time working on the fun parts.*/ | |
var avoidTheFluxBoilerplate = function(name, actionsClass, storeClass) { | |
var actions = this.createActions(name, actionsClass); | |
var store = this.createStore(name, storeClass, this); | |
var actionsToHook = Object.getOwnPropertyNames(actionsClass.prototype); | |
actionsToHook = _.without(actionsToHook, "constructor"); | |
//console.log([" avoidTheFluxBoilerplate", name, actionsToHook, actionsClass, storeClass]); | |
_.each(actionsToHook, function(methodName) { | |
var handlerName = "handle" + methodName[0].toUpperCase() + methodName.slice(1); | |
const actions = this.getActions(name); | |
store.register(actions[methodName], store[handlerName]); | |
}.bind(this)); | |
}.bind(this); | |
// Our app has a few dozen entries which resemble this one. Each has roughly ~5 actions available, so | |
//that would be roughly ~10 lines of boilerplate per. | |
avoidTheFluxBoilerplate("starfighter", StarfighterActions, StarfighterStore); | |
// We could programmatically generate everything from a single string given our naming convention, or introspect for | |
// declared Actions/Stores, but that strikes me as overkill. | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment