Web 组件中的触发事件

Fire events in a web-component

我正在尝试从 Web 组件中引发事件,但确实如此。

<my-component id="xyz" bez="hallo" 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", {
        detail: { name: "John" }
    }));
});
    
shadow.appendChild(button);

谁能帮我找出错误? 非常感谢。

代码-Fiddle 这里:https://jsfiddle.net/b43uqsLp/2/

问题的发生是因为 Shadow DOM(尝试检查您的组件,您会明白我的意思):

好消息,修复起来真的很简单 - 只需在 CustomEvent 的选项中通过 composed: true 属性 将事件传播到阴影 DOM 到常规 DOM 中:

button.dispatchEvent(new CustomEvent("hello", {
    detail: { name: "John" },
    composed: true // Like this
}));

这里是JSFIDDLE

其他答案中缺少一些信息

  • 按钮click监听器在内部阴影DOM,所以composed没有用
  • click 这样的默认侦听器 不会 被 shadowDOM
  • 停止
  • !!! CustomEvents 需要 composed:truebubbles:true 来转义具有 [=96 的自定义元素=]影子DOM.
  • 不要在 connectedCallback 中附加监听器,除非您 100% 确定那是您想要的; connectedCallback 运行 当 DOM 元素在文档中移动时再次出现
  • super()returnsand设置'this',attachShadow()returns and设置this.shadowRoot引用,不需要使用自己的变量。
    运行 super first表示在创建之前不能访问'this';但是你可以 运行 任何你想要的 JS super() 调用之前

这个 JSFiddle:https://jsfiddle.net/CustomElementsExamples/qody0u4n/

显示 composedbubbles 行为,在 document

上有额外的听众
  document.addEventListener("click", (evt) => log(evt, 'document'));
  document.addEventListener("MyEvent", (evt) => log(evt, 'document'));
<my-component id=ONE></my-component>
<my-component id=TWO composed>
    <my-component id=INSIDETWO composed></my-component>
</my-component>
<my-component id=THREE composed bubbles>
    <my-component id=INSIDETHREE composed bubbles></my-component>
</my-component>

笔记

  • none 的 MyEvents 被元素 ONE 或文档捕获

  • composedbubbles 都设置时,文档仅接收 CustomEvent("MyEvent")

  • composed 事件不会在 shadowRoot 边界停止!它在 自定义元素边界 处停止。在 JSfiddle 中 my-component 上有额外的 DOMlisteners 来证明这一点。


另见:https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/