Skip to content

How do you handle user events from the custom element

Gabriel Forti edited this page Jul 31, 2018 · 8 revisions

An alternative to this is:

How can I add event listeners to a HTML element that is inside of a custom element

Consider we have a delete button for a popup message.

<button class="delete" aria-label="delete">Delete</button>

when the user clicks on the delete button we will want to send a custom event listener

function generateTemplate() {
        const template = document.createElement('template');
        template.innerHTML = `<button class="delete" aria-label="delete">Delete</button>`;
        return template;
}

class CustomMessage extends HTMLElement {

    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(generateTemplate().content.cloneNode(true));
      this.btnDelete = this.shadowRoot.querySelector('button.delete')
    }

    connectedCallback() {
        this.btnDelete.addEventListener('click', this.btnClick.bind(this))
    }
    disconnectedCallback() {
        this.btnDelete.removeEventListener('click', this.btnClick.bind(this))
    }

    btnClick() {
        this.dispatchEvent(new CustomEvent('delete-clicked'))
    }
}

window.customElements.define('custom-message', CustomMessage);

Now we can listen for the custom Event and apply a hide class to the custom element to hide it. You can also remove the element from the page. Doing so will have the disconnectedCallback function executed.

document.querySelector('custom-message').addEventListener('delete-clicked', function(){
    console.log('delete clicked')
    this.classList.add('hide')
})
Clone this wiki locally