Skip to content

Removing EventListener's Correctly

Gabriel Forti edited this page Aug 23, 2018 · 1 revision

Be sure that when you add an event listener in the connectedCallback function you will need to also be able to free up memory when the element is removed from the page. This can be done in the disconnectedCallback function, but in order to ensure it is removed we can create a variable in the constructor that will reference the function bind.

    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(generateTemplate().content.cloneNode(true));
      this.todoInput = this.shadowRoot.querySelector('input[name="todo"]');
      this.btnSubmit = this.shadowRoot.querySelector('button');
      this.submitTodoItemBind = this.submitTodoItem.bind(this)
    }

    connectedCallback() {
        this.btnSubmit.addEventListener('click', this.submitTodoItemBind)
    }
    
    disconnectedCallback() {
        this.btnSubmit.removeEventListener('click', this.submitTodoItemBind)
    }

    submitTodoItem() {
        this.dispatchEvent(new CustomEvent('add-todo', { detail: this.todoInput.value }))
    }

Note that the bind method creates a new function, so a reference must be done to ensure it will remove it properly