Skip to content

Instantly share code, notes, and snippets.

Created June 26, 2015 13:39
Show Gist options
  • Save patio11/b472ccb2df3e1fcce78c to your computer and use it in GitHub Desktop.
Save patio11/b472ccb2df3e1fcce78c to your computer and use it in GitHub Desktop.
Got tired of all the boilerplate with hooking up Stores/Actions so...
// 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:
// I use underscore.js below for utility but you can also just do a for loop.
class AppFlux extends Flux {
constructor() {
/* 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]);
// 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