问题描述
我有一个自定义元素 my-checkbox
,该元素包装了复选框,标签,样式等。当切换该复选框时,我定义了 CustomEvent
在我的构造函数中命名为check,例如:
I have a custom element my-checkbox
that wraps a checkbox, label, styling, etc. When that checkbox is toggled I am defining a CustomEvent
named check within my constructor, like so:
constructor(){
super();
this._shadowRoot = this.attachShadow({mode: 'open'});
this.checkEvent = new CustomEvent("check", {
bubbles: true,
cancelable: false,
});
}
我在切换复选框时调度了该事件:
I dispatch that event when the checkbox is toggled:
toggleCheckbox(){
this.dispatchEvent(this.checkEvent);
console.log(this.checkEvent);
...
}
我推断此事件正在调度,因为console.log的内容显示了CustomEvent的签名
I infer that this event is being dispatched because the contents of the console.log show the signature of a CustomEvent
我还有另一个自定义元素 my-checkreport
包含我的复选框,应该对检查事件作出反应。我在 my-checkreport
I have another custom element my-checkreport
that contains my-checkbox and is supposed to react to the "check" event. I have defined an event listener in the connected callback of my-checkreport
connectedCallback(){
...
this.addEventListener("check", function (e) {
console.log('listend to check event');
console.log(e);
});
}
但是,此eventListener从不触发,似乎从不听到检查 事件在 my-checkbox
组件中调度。我试过在构造函数中添加此侦听器,结果相同。
However, this eventListener never fires, never seems to 'hear' the "check" event dispatched in the my-checkbox
component. I've tried adding this listener in the constructor with the same result.
有什么想法我做错了吗?
Any ideas what I'm doing wrong?
背景:我这样做是为了使这些元素可组合。我还读过,开发Web组件的最佳实践是使用自定义事件将信息传递到组件之外……
Background: I'm doing it this way in the interest of making these elements composable. I also have read that best practices for developing web components is to "Use custom events to pass information out of components..."
推荐答案
如果您的复合元素< my-checkreport>
使用Shadow DOM嵌入其内容(< my-checkbox>
,标签,样式...),来自内部元素的调度事件(此处为< my-checkbox>
)将在(容器的)影子DOM内部触发
If your compound element <my-checkreport>
uses a Shadow DOM to embed its content (<my-checkbox>
, label, styling...), dispatched events from an inner element (here <my-checkbox>
) will be fired inside the (container's) Shadow DOM.
因此,应将事件侦听器添加到复合自定义元素( this.shadowRoot
)而不是元素本身( this
)本身。在< my-checkreport>
中:
Therefore, you should add the event listener to the Shadow DOM's root of the compound custom element (this.shadowRoot
) instead of to the element (this
) itself. In <my-checkreport>
:
connectedCallback(){
...
this.shadowRoot.addEventListener("check", function (e) {
console.log('listend to check event');
console.log(e);
});
}
有关Shadow DOM的更多信息:
More on Shadow DOM:
- 对于初学者:
- 很好的总结:
- 规格:
- SO:
- For the beginners: Presentation by Eric Bidelman
- Good summary: Synthesis by Hayato Ito
- Specs: W3C Working Draft
- SO: questions and answers
这篇关于如何监听自定义事件定义的Web组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!