簡體   English   中英

使用 HTMLElement.prototype 添加多個 eventListeners 不起作用

[英]Adding multiple eventListeners using HTMLElement.prototype is not working

我擴展了HTMLElement原型以添加多個eventListener

我的方法

declare global {
  HTMLElement {
    addEventListeners(): any // with a 's'
  }
}

type CallBackFunction<T = void> = () => T

HTMLElement.prototype.addEventListeners() = function(events: Array<HTMLElementEventMap>, callback: CallBackFunction) {
  events.forEach((event) => {
    this.addEventListener(event, callback)
  })
}

但是上面的代碼給我:

  • Type '(events: Array<keyof HTMLElementEventMap>, callback: CallBackFunction) => void' is not assignable to type '() => any'

  • Object is possibly 'undefined'

首先我試過

type CallBackFunction<T = any> = () => T

declare global {
  HTMLElement {
    addEventListeners(): void // with a 's'
  }
}

也解決了第二個錯誤我什至檢查了但仍然沒有運氣!

if (typeof this !== 'undefined') {
  this.addEventListener(event, callback)
}

他們期望 function 什么都不返回(無效)。 所以,試試這個

我想這就是你要找的

declare global {
  interface HTMLElement {
    addEventListeners<K extends keyof HTMLElementEventMap>(type: K[], listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
  }
}

HTMLElement.prototype.addEventListeners = function (events, listener) {
  events.forEach((event) => {
    this.addEventListener(event, listener);
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM