Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  24] [ 7]  / answers: 1 / hits: 33097  / 7 Years ago, tue, march 28, 2017, 12:00:00

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);
...
}


I infer that this event is being dispatched because the contents of the console.log show the signature of a CustomEvent



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);
});
}


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?



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...


More From » dom

 Answers
16

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.



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);
});
}


More on Shadow DOM:




[#58358] Sunday, March 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;