To override a public function that has been defined using function syntax, you must assign to it in the global scope. This is because JavaScript will not allow replacing a function using a variable that points to the function.

Given the following function:
function doWork(myVariable) {
   console.log('Do some work... ' + myVariable);
   return "foo";
}
doWork('Widget'); // output: Do some work... Widget

We can override the function behavior, with the option to invoke it while preserving original arguments and 'this', using the following syntax:
doWork = $(document).override(doWork, function(arguments, oldFunction) {
   console.log('Hello from overriding function.');
   //Calling oldFunction() without any arguments will pass the original arguments to the function and use the original 'this' 
   oldFunction();
   console.log('All finished.');
}
doWork('Gadget');
//output: 
//Hello from overriding function.
//Do some work... Gadget
//All finished.

Functions that are already overridden by jQuery.override can be subscribed and unsubscribed to.
When the function is invoked, there is the option to cancel it using a subscription. The function must already have been overridden using the syntax above.
var cancelFunction = false;
$(document).override(doWork, 'subscribe', function (event) {
	console.log('Hello from subscriber');
	if (cancelFunction) {
		console.log('Cancelling call to the original function.');
		event.cancel = true;
	}
});
doWork('Gizmo');
//output:
//Hello from subscriber
//Hello from overriding function.
//Do some work... Gadget
//All finished.
cancelFunction = true;
doWork('Sprocket');
//output:
//Hello from subscriber
//Cancelling call to the original function.

A function can be restored to its original state using the following syntax:
doWork = $(document).override(doWork, 'restore');
doWork('Whatsit');
//output:
//Do some work... Whatsit

Last edited Dec 24, 2012 at 8:17 PM by aikeru, version 1

Comments

No comments yet.