16

I know it is possible to add an event listener to a custom event that I have created in Javascript, like this:

window.addEventListener("MyCustomEvent", myFunction, false);

But...Is it possible to list All custom events that exist at any point?

The above line adds an event listener regardless of whether the event exists or not, so I cannot indicate if the event exists or not.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Oli C
  • 1,120
  • 13
  • 36
  • 5
    No, it's not possible. The console in the browser should be able to list them, Chrome has [getEventListeners](https://developer.chrome.com/devtools/docs/commandline-api#geteventlistenersobject) etc, but it's only for use in the console, in your script there's no way to list the event listeners added. – adeneo Jul 31 '14 at 16:02
  • Thanks adeneo. I Am actually trying to debug via the console, but the above command does not seem to work whilst in debug mode...Let me explain further- I am having to use JQuery event triggers to create my custom events, as creating them via Javascript is not supported in the Android native browser... I would rather not use JQuery CustomEvents, so I have been trying to work out how JQuery itself creates the events, but introspection into the JQuery code can be kind of confusing..! – Oli C Aug 01 '14 at 11:34

1 Answers1

13

This is generally a bad idea, but if you really have the need for this, you could override the addEventListener function like this to keep track of the events added:

var events = {};
var original = window.addEventListener;

window.addEventListener = function(type, listener, useCapture) {
    events[type] = true;
    return original(type, listener, useCapture);
};

function hasEventBeenAdded(type) {
    return type in events;
}

Keep in mind that this will only work for code that adds event listeners after this piece of code is included.

Overv
  • 8,433
  • 2
  • 40
  • 70
  • Hi Overv, thanks for your response, though maybe I wasn't as clear as I should have been- My comment above explains better what I require- I am debugging to find out how JQuery creates custom events, so I can take that code and implement it in Javascript. – Oli C Aug 01 '14 at 13:10