How to use getEventListeners in Chrome Dev Tool?

那年仲夏 提交于 2020-01-22 17:28:46

问题


I tried to trace back which function hooked into a click event of .someclass. I open Chrome Dev Tool and type this

getEventListeners(document.querySelector('.someclass'));

The result is this

Object {}

I cannot click and open it to find out the name of the object or the source code that handle click event.

Is there a way to find out?

UPDATE 1:

Followed Krasimir's advise below. There could be only two events: mousemove or mouseover. So how do I find out the exact function handling that event for canvas.overlay? There are just too many to drill down into.


回答1:


  1. Open the DevTools
  2. Open the Elements tab and locate your element (.someclass)
  3. There are four tabs per element - Styles, Properties, DOM Breakpoints and Event Listeners
  4. Select Event Listeners




回答2:


You are getting an empty object when calling

getEventListeners(document.querySelector('.someclass'));

probably because the listener isn't hooked up to .someclass element itself (direct event), but to one of it's ancestors (delegated event). There is a good explanation of this here.

You can list both delegated and direct events by calling getEventListeners for specified node and all it's ancestors. This function should do the trick:

getAllEventListeners = function(el) {
 var allListeners = {}, listeners;

 while(el) {
  listeners = getEventListeners(el);

  for(event in listeners) {
   allListeners[event] = allListeners[event] || [];
   allListeners[event].push({listener: listeners[event], element: el});  
  }

  el = el.parentNode;
 }

 return allListeners;
}

However, this will output exactly the same thing as the "Event Listeners" tab (with "Filter" option set to "All nodes") that Krasimir mentioned in his answer.




回答3:


I guess you are using jQuery to bind the events to that element. That's why you can't see the actual handler code in the drill down menu. Without wrapped by jQuery, the actual code should be displayed in "listenerBody" like this:



来源:https://stackoverflow.com/questions/18544306/how-to-use-geteventlisteners-in-chrome-dev-tool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!