I'm creating an element and then want to add an event listener to it. I'm doing:
console.log('about to create modal');
this.createModal(
'There are unsubmitted changes in this Access Request.',
'Do you wish to discard them?',
'Yes',
'No',
'tabCloseModal'
);
console.log('created modal');
const modal = this.shadowRoot.querySelector('#tabCloseModal');
console.log(`modal = ${modal}`);
modal.addEventListener('px-modal-accepted', function(e) {
console.log('removing tab');
this.removeTab(index);
});
Where createModal
creates an element:
createModal(headerText, bodyText, acceptText, rejectText, id, opened = true) {
const modal = document.createElement('px-modal');
//assign parameters
document.swQuerySelector('body').appendChild(modal);
console.log('Child appended');
modal.visible = true;
this.fire('modal-visible');
}
No matter what I do (I tired swQuerySelector
, swQuerySelectorAll
, querySelector
, querySelectorAll
), I can't seem to get a hold of the modal. When I log it it just shows up as either empty, undefined or [object Object] or something like that, and I never get to 'removing tab'. What am I missing? The modal is showing up, but the mapping of the accepted event listener does not work.
To solve this:
Return the modal from createModal
, and confirm it works as expected in the calling code.
If it does, the problem is in your this.shadowRoot.querySelector
line. Set a breakpoint at that point and try some paths to querySelector
in the devtools command line
until you get your modal. Try to find the modal in your devtools elements
window to see where it lies. Without seeing a layout of your DOM, we cannot suggest the the exact path to the parent element.
The Shadow DOM can get 'shady' at times...