Skip to content

Instantly share code, notes, and snippets.

@glortho
Last active August 29, 2015 14:26
Show Gist options
  • Save glortho/b3e3a06761daefeca110 to your computer and use it in GitHub Desktop.
Save glortho/b3e3a06761daefeca110 to your computer and use it in GitHub Desktop.
Dispatch decorators for Flux
/**
* Dispatch decorators for Flux (using ES2016 via Babel stage 1)
*
* There are some nice things about this:
*
* 1. Action types are specified at design time.
* 2. Any method's return value can be dispatched by prepending the decorator, without breaking up method definition itself.
* 3. Easier testing of action creator methods by forcing return value + simpler mocking of dispatch.
* 4. Easier grokking of all actions attached to a given class.
*/
let dispatch = ( ACTION ) => {
return function( target, key, descriptor ) {
let method = descriptor.value;
descriptor.value = function( ...args ) {
let result = method.call( target, ...args );
myDispatchFn( ACTION, result );
return result;
};
return descriptor;
};
};
class MyClass {
@dispatch( 'SOME-ACTION-TYPE' )
someActionCreator( someArg ) {
// possibly some other logic in here
return { someKey: 'someValue' };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment