I am trying to extend a third party library on a specific page, but I don't want to change any of the third party code. I know the name of the functions the third party library calls when something happens, so if I want my own custom code to execute after that, how can I do that?
Third Party Library has:
function eventFinished(args){
//library stuff here
}
Now if it was my own code I'd do something like this:
function eventFinished(args){
//library stuff here
MyCustomFunction();
}
However, it's not and I don't want to overwrite stock library code. So is there anyway to do the above, but without touching the original function code? I would have a reference to the function itself, but that's it.
EDIT: I should mention the declared function is available globally.
click(function(){ if (condition == 'true'){ function1(someVariable); function2(someOtherVariable); } else { doThis(someVariable); } });
If we have three synchronous functions, we can execute them asynchronously using the setTimeout function. setTimeout(doSomething, 10); setTimeout(doSomethingElse, 10); setTimeout(doSomethingUsefulThisTime, 10);
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
It is also common to say "call upon a function", "start a function", or "execute a function". In this tutorial, we will use invoke, because a JavaScript function can be invoked without being called.
If there is a way for you to get a reference to the function you want to extend you can "monkey-patch" it like this:
var fnOriginalFunction = functionYouWantToExtend;
functionYouWantToExtend = function() {
fnOriginalFunction.apply(this, arguments);
// your code here
};
This effectively re-writes the function you want to extend in a somewhat-seamless manner.
More information about monkey-patching.
"I am trying to extend a third party library on a specific page, but I don't want to change any of the third party code"
This can't be done. You have to alter the code somehow to react to it unless the code provides an event emitting mechanism or something alike.
The way to approach this without affecting the library is to overwrite the function you want to extend by having it do everything it already did and add your custom behavior on top.
For example:
const Library = {
method() {
console.log('I am the library method');
}
}
const unalteredMethod = Library.method;
Library.method = function() {
unalteredMethod.apply(this, arguments);
console.log('my custom behavior');
}
Library.method();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With