如何查看将事件处理程序添加到元素中? [英] How can I watch Event Handlers being added to an Element?

查看:38
本文介绍了如何查看将事件处理程序添加到元素中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个错误,看起来像是由附加了click事件的事件处理程序引起的:

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");

我想看看如何添加Element的事件处理程序(以及何时添加)

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

我在Chrome调试器(Dev工具)>元素中找到了它,然后选择中断属性修改".调试器永不中断.

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

我还选择了它的父Div(位于其中)并设置Debugger(在Element上单击鼠标右键)>中断子树修改.再次,它永不中断.

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.

我在做什么错了?

推荐答案

添加事件侦听器通常不是属性更改-而是通常是对 addEventListener 上-分配.因此,听属性更改将无效.

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.

一个选择是猴子补丁 addEventListener ,以便在使用匹配参数调用 addEventListener 时,运行 debugger .例如:

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>

这篇关于如何查看将事件处理程序添加到元素中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆