【问题标题】:Re-bind onclick, on* event listeners for debugging重新绑定 onclick, on* 事件监听器进行调试
【发布时间】:2020-06-07 06:00:27
【问题描述】:

我想对事件监听器注册进行monkeypatch。

我发现this answer 展示了如何为addEventListener 做这件事:

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');
});

但这不会涵盖onclickonkeydown 等作业。

我不知道该怎么做,因为

const nativeOnClick = HTMLElement.prototype.onclick;

抛出类型错误

TypeError: 'get onclick' called on an object that does not implement interface HTMLElement.

现在我想知道是否有一种特殊的方法可以特别地单独检索onclick 等的setter 和getter,但到目前为止我的google 搜索都没有运气。 p>

【问题讨论】:

    标签: javascript dom-events getter-setter setter


    【解决方案1】:

    您可以通过以下方式获得原始的 setter 函数:

    const originalSetter = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onchange').set;
    

    如果你想重新定义一个属性,你应该考虑使用Object.defineProperty()

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      相关资源
      最近更新 更多