I'm currently rendering a component in vanilla JS by calling a method attached to a class where the component is defined, and returned.
class ToastNotification {
constructor(paramsObj) {
this.notificationType = paramsObj.notificationType || "info";
this.notificationAction = paramsObj.notificationAction || "none";
this.title = paramsObj.title || "Something happened";
this.message = paramsObj.message || `Here's some more specific information on what happened`;
}
getHtml() {
return `
<div
class="toastNotification notification_${this.notificationType} ${this.enableAnimations()}"
>
<div class="notification_icon">
<ion-icon name="${this.icon}"></ion-icon>
</div>
<div class="notification_text">
<p class="text_title">${this.title}</p>
<p class="text_message">${this.message}</p>
<p class="text_time">${this.timeSinceNotification()}</p>
</div>
<div class="notification_close">
<ion-icon name="close" onclick="this.closest('.toastNotification').remove()"></ion-icon>
</div>
</div>
`;
}
}
But how can I add an event listene or set a timeout to take an action on the component, after I have called the getHTML() method to render the element?
As I would like to be able to set a timeout for the rendered element to dissapear after X amount of time and add an event listener to enable different actions when clicked on. But I am open to alternatives if they can get the same job done.
The best result I've come up with so far is using the MutationObserver.
const observer = new MutationObserver((change) => {
change[0].addedNodes.forEach( newNode => {
if (newNode.tagName == 'DIV' && newNode.classList.contains('toastNotification')) {
// Add listeners or do an action
}
});
});
And then attaching the observer to the HTML document, or the body
observer.observe(document.querySelector('html'), {attributes: false, childList: true, subtree: true,});