Skip to content

Instantly share code, notes, and snippets.

@michealbenedict
Last active December 9, 2015 23:29
Show Gist options
  • Save michealbenedict/4344855 to your computer and use it in GitHub Desktop.
Save michealbenedict/4344855 to your computer and use it in GitHub Desktop.
Sugar code to help write simpler callback functions.
/**
* `C` constructor
*
* Proposed Simpler API for callback functions within a function
*
* // Old style
* someFunction(1, function success () {
* console.log('success callback')
* }, function fail () {
* console.log('fail callback')
* });
*
* // Proposed Refactored Style
* someFunction(1)
* .success(function () {
* console.log('success callback')
* })
* .fail(function () {
* console.log('fail callback')
* })
* .exec();
*
* Goal:
* 1. Simple API
* 2. Support for Old Style
*
* Usage:
*
* Define your functions
* var someFunction = function ( params, successCallback, failCallback ) {
* console.log('this is the function', params);
* // after some random logic
* // if ( some condition )
* successCallback();
* // some other async call
* failCallback();
* });
*
* someFunction = new Function(['success', 'fail'], someFunction);
*
* @param {Array} callbacks - array of callback names
* @param {Function} fn - Function which should support refactored style syntax
*/
function Q ( callbacks, fn ) {
var self = this;
self._fn = fn;
self._args = [];
return function () {
var _callbacks = {};
self._args = Array.prototype.slice.call(arguments);
// * This line enables old style function call
// return self._fn.apply(self, arguments);
callbacks.forEach(function ( name ) {
// callback function assignment
self[name] = function (cb) {
_callbacks[name] = cb;
// push args
self._args.push(_callbacks[name]);
return self;
};
});
// call function after calling all other callbacks !important
return self;
};
}
Q.prototype.exec = function () {
return this._fn.apply(this, this._args);
}
var F = function (fn) {
new Q(fn);
}
// Some Function
var someFunction = function ( params, callback1, callback2 ) {
console.log('this is the function', params);
// after some logic
// call success or fail
callback1();
// some other async call
callback2();
}
// Augment someFunction
someFunction = F(someFunction);
// Call
someFunction(1)
.callback1(function () {
console.log('success callback')
})
.callback2(function () {
console.log('fail callback')
})
.exec();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment