5

JavaScript doesn't have an hasEventListener function. What can I use in its place?

I'm doing:

someForm.addEventListener( "submit", _submitHandler, false );

And I have a "forms controller", which should test which forms have a listener for the submit event.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Ratata Tata
  • 2,781
  • 1
  • 34
  • 49
  • 1
    You're probably doing something wrong. Events should be dispatched even if nobody is listening for them. Provide more details about your underlying logic. – lanzz Jun 22 '12 at 12:57
  • 1
    It's actually not that easy: I suggest checking [this answer](http://stackoverflow.com/a/447106/1229023) to see the explanation why. ) – raina77ow Jun 22 '12 at 12:58
  • @raina77ow, appears to not be possible, as wanted. There is no hasEventListener and willTrigger in js. =\ – Ratata Tata Jun 22 '12 at 13:06
  • Well, if what you want is just add some nice method showing all the events for the original page, I guess you're out of luck. Yet it's technically possible to 'highjack' the addEventListener, as shown [here](http://stackoverflow.com/a/6434924/1229023). May be that'll help. ) – raina77ow Jun 22 '12 at 13:11
  • This sounds like an A/B question. Why do you want to check for event listeners? Could you provide more information about your problem? I suppose we may never get additional information since this question is almost 7 years old. – zero298 Feb 08 '19 at 17:13

1 Answers1

1

If you think that a particular element has a listener on it (and you have to have a reference to the listener), then just call removeEventListener() with the event type and the listener reference. The call won't do anything if there's no listener (or the reference is incorrect), so it's not exactly the best-performance choice, but it does work.

user1329482
  • 569
  • 3
  • 8