send event object via `dispatch` in vuex?

Viewed 55

If an addEventListener callback is passed, for example, via an arrow function, then everything works, but then I cannot remove the listener via removeEventListener.

export const actions = {
  open() {
    document.querySelector('nav').classList.add('open')
    document.addEventListener('click', (e) => this.dispatch('clickListener', e))
  },
  close() {
    document.querySelector('nav').classList.remove('open')
    document.removeEventListener('click', (e) => this.dispatch('clickListener', e))
  },
  toggle() {
    if (document.querySelector('nav').classList.contains('open')) {
      this.dispatch('close')
    } else {
      this.dispatch('open')
    }
  },
  clickListener(ctx, e) {
    console.log(e);
  },
}
1 Answers

The problem is you're creating a new anonymous function in each call to addEventListener and removeEventListener, so removeEventListener is not able to find the originally created callback.

Instead of the inline anonymous function, cache the created callback that is passed to addEventListener so that the cached result could be later passed to removeEventListener:

let clickHandler = null

export const actions = {
  open() {
    // remove any existing callback (null ignored)
    document.removeEventListener('click', clickHandler)

    clickHandler = (e) => this.dispatch('clickListener', e)
    document.addEventListener(j'click', clickHandler)
  },
  close() {
    document.removeEventListener('click', clickHandler)
    clickHandler = null
  }
}
Related