Search code examples
javascripthtmlevent-handlingdom-eventsweb-component

How do HTML event handler attributes work?


just got question about how does HTML works.

As far as I know, attribute of HTMLElement is only 'string | null'

but as we know, on HTML


<div onclick="sayHi()" />

works.

I'm wondering, how does 'sayHi' string gets map into actual function object.

and in advance, for web components, can we pass functions to web-component attributes? not using global object as proxy?


Solution

  • That MDN link is wrong (IMHO) when it says those type of inline events should not be used.

    https://javascript.info/introduction-browser-events has a better and more complete explanation.

    this.onclick = (evt) => { } is perfectly valid when used in the connectedCallback of a Web Component,
    because the outside world should not have anything to do with a Web Components internals, and this.addEventListenerer("click",(evt=>{ }); (which does the same, but allows for multiple events) is just longer,
    and implies using a not required removeEventListener because listeners on DOM nodes (the Web Component) are garbage collected, thus automatically removed.

    Note <my-component onclick=" "> is a different notation for the same this.onclick handler. If you really need to add a click handler in HTML you might want to do <my-component onclick="this.getRootNode().METHOD()"> to call a method on your Web Component.

    this.onclick = ()=>{ } will override your HTML defined handler.

    NOTE

    thanks for reminding me, Kaiido

    • <my-component onclick="function()"> runs in global scope

    • and this.onclick runs in component scope