'HTMLElementWrapper solution for extending prototype -- adding new functions

The problem is quite simple:

add two functions to the HTMLElement which is on and off.

The on functions works exact same as addEventListener

The off functions works exact same as removeEventListener.

One quick solutions is:

HTMLElement.prototype["on"] = HTMLElement.prototype.addEventListener;
HTMLElement.prototype["off"] = HTMLElement.prototype.removeEventListener;

this works fine but since I am using typescript I will get a error in vscode saying:

Property 'on' does not exist on type 'HTMLElement'

I do not know how to solve this error in vscode but it works fine anyway.

Then I tried another way to create a wrapper class as below:

export class HTMLElementWrapper {
    dom: HTMLElement;
    constructor(dom) {
        this.dom = dom;
    }

    on(...args) {
        HTMLElement.prototype.addEventListener.call(this.dom, arguments);
    }

    off(...args) {
        HTMLElement.prototype.removeEventListener.call(this.dom, arguments);
    }
}

If I do this I will not get the error in vscode again but when I wrong the code I will get the error in runtime:

TypeError: Failed to execute 'addEventListener' on 'EventTarget': 
2 arguments required, but only 1 present.

I am not sure how to solve this.

Any suggestion will be appreciated, thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source