Reputation: 674
My client's webshop has a custom product configurator which has a window.build_preview
function.
This method can be called whenever, but I want to check when it's called.
jQuery has an .on
method, but it only applies to DOM eventlisteners.
Is it possible to listen for function calls in JS? For example:
$(window).on(build_preview(), function() {
alert('Function has been called somewhere else!');
})
Upvotes: 0
Views: 233
Reputation: 171679
You can overload the original function and trigger a custom event in the new version and add an event listener for the custom event.
Just make sure that the original is already declared prior to your overload code
// original function declaration
window.build_preview = function(){
console.log('.build_preview() called')
}
// store reference to original function
const origFn = window.build_preview
// overload the function
window.build_preview = function(){
// call original
origFn();
// trigger custom event
$(window).trigger('build_preview')
}
// custom event listener
$(window).on('build_preview', function(){
console.log('event triggered from build_preview() call');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="build_preview()">Click me</button>
Upvotes: 1
Reputation: 156
You can create and dispatch a custom event
const event = new Event('build_preview');
// Listen for the event.
window.addEventListener('build_preview',
function (e) {
alert("function has been called somewhere else")
},
false);
// Dispatch the event inside your function build_preview so that whenever it
// is called this event is emitted.
window.dispatchEvent(event);
for more info check this
Upvotes: 1