Created
April 25, 2013 07:34
-
-
Save g0ody/5458106 to your computer and use it in GitHub Desktop.
Angularjs Callback Service (Method Chaining and Custom Callbacks)
This file contains hidden or 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
/*global _, angular */ | |
/* | |
function send() { | |
var cb = new Callback("custom"); | |
SomeService.Send(cb.triggerSuccess, cb.triggerError, cb.triggerCustom); | |
return cb.remote(); | |
} | |
send() | |
.success(function(data){}) | |
.error(function(data){}) | |
.custom(function(data){}) | |
.complete(function(data){}) | |
*/ | |
angular.module('callbackServices', []) | |
.factory('Callback', function ($timeout){ | |
return function(custom){ | |
var successCallbacks = []; | |
var errorCallbacks = []; | |
function capitaliseFirstLetter(str) { | |
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); | |
} | |
function invokeCallbacks(callbacks, data) { | |
$timeout(function(){ | |
_.chain(callbacks).compact().each(function(callback) { callback(data); }); | |
}, 0); | |
} | |
var baseRemote = { | |
chain:function(callback){ return this.success(callback.triggerSuccess).error(callback.triggerError); }, | |
success: function(callback) { successCallbacks.push(callback); return this; }, | |
error: function(callback) { errorCallbacks.push(callback); return this; }, | |
complete: function(callback) { return this.success(callback).error(callback); } | |
}; | |
var base = { | |
triggerSuccess:function(response){ | |
invokeCallbacks(successCallbacks, response); | |
return this; | |
}, | |
triggerError:function(response) { | |
invokeCallbacks(errorCallbacks, response); | |
return this; | |
}, | |
remote: function(){ return baseRemote; } | |
}; | |
var customCallbacks = {}; | |
function addCustomCallback(key){ | |
customCallbacks[key] = []; | |
baseRemote[key] = function(callback) { customCallbacks[key].push(callback); return baseRemote; }; | |
base["trigger" + capitaliseFirstLetter(key)] = function (response) { invokeCallbacks(customCallbacks[key], response); }; | |
} | |
if(angular.isArray(custom)){ | |
_.each(custom, addCustomCallback); | |
} else if( angular.isString(custom)){ | |
addCustomCallback(custom); | |
} | |
return base; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment