This content resides within the legacy JavaScript files that are not meant to be altered:
// Here lies the untouched, original function
function originalFunction(sel) {
alert(sel);
$(sel).css("display","none");
}
Here is the modified portion in your code:
// Example callback function to be passed into the extended function below
function myCallback(s) {
alert("The image with src = '" + $(s).attr("src") + "' has been modified!");
}
// Extension of the function without directly modifying it
originalFunction = (function(legacyFn, callback) {
// Single argument function to be assigned back to originalFunction
return function(sel) {
// Call the "original" originalFunction, triggering alert and hiding image.
legacyFn(sel);
if(callback) callback(sel); // Execute the callback function
}
})(originalFunction, myCallback);
The variable originalFunction
now holds a function accepting one parameter. This function is returned by a self-executing anonymous function which takes two arguments: the reference to the original originalFunction
before any modifications, and the reference to the callback
function. These references are enclosed within the closure to maintain their values even after reassigning originalFunction
.
To summarize, at a higher level, originalFunction
and myCallback
are inputs for the self-executing function, stored in legacyFn and callback respectively. A new function is then assigned to originalFunction
.
When you invoke
originalFunction('.someClassOnAnImage')
, the legacyFn triggers, displaying an alert with the selector and hiding the image. Subsequently, if present, the callback function will execute, printing:
The image with src = '.someClassOnAnImage' has been modified!
Although lacking the elegance of addEventListener, this method enables customization of legacy functions without tampering with the original source files. It extends functionality while preserving the original functions intact.
You can neatly store all extensions in a separate JavaScript file or within your current script. To revert to the default behavior, simply delete your additional functions.