<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<div ng-app="Demo" ng-controller="AppController">
<h1>Monkey-Patching The $q Service With .fcall() In AngularJS</h1>
<p><em><storng>Note</strong>: This is not exactly the .fcall() method from Q. Rather, this is inspired by that concept.</em>
</p>
</div>
// Create an application module for our demo.
var app = angular.module("Demo", []);
// I monkey-patch the .fcall() method into the root of the $q service. We have
// to do this in a .run() block so that it will modify the $q service before any
// other component in the application needs it.
app.run(
function monkeyPatchQService($q, $exceptionHandler) {
// I invoke the given function using the given arguments. If the
// invocation is successful, it will result in a resolved promise; if it
// throws an error, it will result in a rejected promise, passing the
// error object through as the "reason."
// --
// The possible method signatures:
// --
// .fcall( methodReference )
// .fcall( methodReference, argsArray )
// .fcall( context, methodReference, argsArray )
// .fcall( context, methodName, argsArrray )
// .fcall( context, methodReference )
// .fcall( context, methodName )
$q.fcall = function () {
try {
var components = parseArguments(arguments);
var context = components.context;
var method = components.method;
var inputs = components.inputs;
return ($q.when(method.apply(context, inputs)));
} catch (error) {
// We want to pass the error off to the core exception handler.
// But, we want to protect ourselves against any errors there.
// While it is unlikely that this will error, if the app has
// added an exception interceptor, it's possible something could
// go wrong.
try {
$exceptionHandler(error);
} catch (loggingError) {
// Nothing we can do here.
}
return ($q.reject(error));
}
};
// ---
// PRIVATE METHODS.
// ---
// I parse the .fcall() arguments into a normalized structure that is
// ready for...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.