0

I was reading through the solution to a question about finding registered event handlers on an object, and it nearly solved my problem.

My problem extends a bit further though - I now want to know the state of each of these event handlers. Are they (or some of them) still listening, have they started executing, or are they finished executing.

EDIT: "working" code to get the registered events:

$._data( document.body, "events" )["customEventName"]

To explain my motivation, and/or if you are bored, please check out my related post. I was hoping to debug further, and/or kill mid-action listeners, based on the answers to this question.

A554551N
  • 145
  • 1
  • 2
  • 10
  • 2
    If they exist, they are still listening for events. Also, given that the handler should execute in a few milliseconds, and that JS is in effect single-threaded, the chances of you retrieving the data of the events when one is actually being executed are almost zero. I'm not sure what you're attempting to do with this logic, but your goal seems a little confused. – Rory McCrossan Dec 05 '18 at 22:39
  • 1
    Side note; `$('body')[0]` === `document.body` 0_0 – Taplar Dec 05 '18 at 22:52
  • @RoryMcCrossan - no arguments there. My goal is a little confused. I have updated the post to include a link to explain my motivation, but the short story is that I think if I can interrupt currently-running listeners/handlers, or wait for them all to be done, then I can avoid what I think is a rare race condition. – A554551N Dec 06 '18 at 15:23
  • @Taplar - thanks, I have incorporated that into the post to make it more correct moving forward. – A554551N Dec 06 '18 at 15:26

1 Answers1

0

If they exist, the events are still being listened to. As for the state you mention I doubt you can get anything meaningful from them.

Depending on what your use case is you could overload the handler(s) to intercept them though.


Example to overload all event listeners on a specific element:

var $btn = $('button').on('click mouseenter',function(e) {
  console.log('Original event handler')
});

var buttonEvents = $._data($btn[0], 'events');

Object.keys(buttonEvents).forEach(function(k) {
  buttonEvents[k].forEach(function(o) {
    var oldHandler = o.handler;
    o.handler = function(e) {
      console.log('Event Type: ', e.type, ' new handler');
      if(arguments[1]){
         console.log('Event Data:: ', arguments[1]);
      }
      oldHandler.apply(this, arguments);
    };
  });
});

$btn.trigger('click', ['Triggered click'])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>
click me
</button>
charlietfl
  • 170,828
  • 13
  • 121
  • 150