Web组件中的火灾事件 [英] Fire events in a web-component
问题描述
我正在尝试从Web组件引发事件,但是确实如此.
< my-component id ="xyz"bez =你好"hello ="myScript()"</my-component>< script>xyz.addEventListener("hello",function(event){console.log(event.detail.name);});</script>
html标签"hello"都没有确实引发了事件,事件监听器也没有.
Web组件如下所示:
var button = document.createElement("button");button.innerHTML = cap;button.addEventListener('click',()=> {console.log("click");button.dispatchEvent(new CustomEvent("hello",{详细信息:{名称:"John"}}));});shadow.appendChild(button);
有人可以帮助我发现错误吗?非常感谢.
代码提琴在这里:
好消息,它真的很容易解决-只需通过CustomEvent选项中的 composed:true
属性将事件跨阴影DOM传播到常规DOM中即可.
button.dispatchEvent(new CustomEvent("hello",{详细信息:{名称:"John"},组成:true//像这样}));
这里是 JSFIDDLE .
I am trying to raise events out of a webcomponent, but it does.
<my-component id="xyz" bez="hallo" hello="myScript()"></my-component>
<script>
xyz.addEventListener("hello", function(event) {
console.log(event.detail.name);
});
</script>
Neither the html-tag "hello" does raise the event, nor the event-listener does.
The web component looks like this:
var button=document.createElement("button");
button.innerHTML=cap;
button.addEventListener('click', () => {
console.log("click");
button.dispatchEvent(new CustomEvent("hello", {
detail: { name: "John" }
}));
});
shadow.appendChild(button);
Can anyone help me please to find the mistake? Thanks a lot.
Code-Fiddle here: https://jsfiddle.net/b43uqsLp/2/
The problem occurs because of the Shadow DOM (try to inspect your component and you will see what I mean):
Good news, it's really simple to fix - just propagate the event across the shadow DOM into the regular DOM via composed: true
property in your CustomEvent's options:
button.dispatchEvent(new CustomEvent("hello", {
detail: { name: "John" },
composed: true // Like this
}));
Here is JSFIDDLE.
这篇关于Web组件中的火灾事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!