Home > Software engineering >  Adding multiple eventListeners using HTMLElement.prototype is not working
Adding multiple eventListeners using HTMLElement.prototype is not working

Time:12-29

I extended HTMLElement prototype for adding multiple eventListener.

My Approach

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

but the above code giving me :

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

  • Object is possibly 'undefined'

For first I tried

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

also

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

and too solve second error I even put a check but still no luck!

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

CodePudding user response:

I think this is what you are looking

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

Usage

document.querySelector('button').addEventListeners(['click', 'focus'], () => {
 //do something
});

CodePudding user response:

they expect that the function return nothing (void). so, try this

  • Related