问题
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