Question

Is is possible to listen if a function was fired up in another .js file?

For example function foo() was fired.

Is it possible to run a piece of code everytime foo() is run without placing the code I want to run within that function?

Was it helpful?

Solution 2

What you need to know about is javascript events. How to create your own event and trigger it.

See this answer for a good start

What you want to do is have the function trigger an event (let's say funcCalled) and in your main app add a listener for the that event. The listener can then dispatch instructions based on what you need.

OTHER TIPS

Although dops above pointed me to the right answer, I'll drop a cross-browser compatible way of doing this.

First we need to dispatch an event from the function that is-to-be listened if fired.

(The following snippet goes into the function to be listened on)

// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
document.dispatchEvent(event);

Second, we need to add an eventListener to listen if the function was fired:

document.addEventListener("name-of-event", function(e) {
  console.log(e.detail); // Prints "Example of an event"
});

Now this works just fine in FF/Chrome but IE doesn't support it. So we need to create a polyfill for it.

Just put this function anywhere in your script and IE will support the above snippets of code.

(function () {
  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   };

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();

Sources:

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

How to trigger event in JavaScript?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top