How can I watch Event Handlers being added to an Element?

萝らか妹 提交于 2021-02-05 06:42:08

问题


I've got a bug that looks like it's caused by an Event handler being attached a click event:

 mxpnl.track_links("#pagebody a", "Click.body");

I'd like to watch to see how that Element's event handler is added (and when)

I found it in the Chrome Debugger (Dev Tools) > Elements and choose Break on Attribute modifications. Debugger never Breaks.

I also selected it's Parent Div (that it is within) and set Debugger (right-click on Element) > break on subtree modifications. Again, it never breaks.

What am I doing wrong here?


回答1:


Adding an event listener isn't an attribute change (often) - rather, generally it's a call to addEventListener or an on- assignment. So, listening to attribute changes won't work.

One option would be to monkeypatch addEventListener so that debugger runs when addEventListener is called with the matching arguments. For example:

// snippet might not actually enter the debugger due to embedded sandboxing issues

const nativeEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(...args) {
  if (this.matches('div') && args[0] === 'click') {
    console.log('listener is being added to a div');
    debugger;
  }
  nativeEventListener.apply(this, args);
}



// then, when an event listener is added, you'll be able to intercept the call and debug it:

document.querySelector('div').addEventListener('click', () => {
  console.log('clicked');
});
<div>click me</div>



回答2:


In very simple term if explain then event listeners is just a function which add in an array with reference of string such as "click" and "on" etc..

So when you say.....

  function myClick1(){
  console.log('myclick1 called');
}  
 document.querySelector('mydiv').addEventListener('click', myClick1);
    function myClick2(){
          console.log('myclick2 called');
        }
document.querySelector('mydiv').addEventListener('click', myClick2);

it add the function myClick1 and myClick2 in event listener array for click and execute in sequence as it added.

AND YOU CAN USE PROTOTYPE OF EVENT TARGET TO MONKEY PATCH THE EVENT LISTENER ARRAY.



来源:https://stackoverflow.com/questions/52417142/how-can-i-watch-event-handlers-being-added-to-an-element

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