英文:
How do HTML event handler attributes work?
问题
刚刚有关于 HTML 如何工作的问题。
据我所知,HTMLElement 的属性仅限于 'string | null'。
但我们知道,在 HTML 上,
<div onclick="sayHi()" />
能够工作。
我想知道,'sayHi' 字符串是如何映射到实际函数对象的。
提前说一下,对于 web 组件,我们能将函数传递给 web 组件属性吗?而不是使用全局对象作为代理?
英文:
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?
答案1
得分: -2
以下是您要翻译的内容:
"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.addEventListener("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"
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论