thierrymichel / kapla

Tiny JS framework to manage DOM components
The Unlicense
61 stars 2 forks source link

Custom events that not unbind #10

Closed gfnool closed 2 years ago

gfnool commented 2 years ago

Hi (and thanks for Kapla!)

I've found these two problems related to events. I've build a repo to test them and show you the code: https://github.com/gfnool/kapla-test

  1. If a component is listening to two custom 'global' events, when the component is destroyed only one of the event is unbind. This does not happen if the custom event type is 'component' https://kapla-test.netlify.app/global-events.html

  2. If a dom node has two components attached and they are listening to the same custom event, when the node is destroyed only one of the listener is unbind. https://kapla-test.netlify.app/same-node.html

Are they known bugs? Is there a better way to use global events?

Thank you!

thierrymichel commented 2 years ago

Hi Giorgio,

Thanks for your detailed report! 👌

  1. You can try with 2.1.7
  2. eventByElement is a map. That means one key (element) for one value (event), so you can not store (and then get for the removeEventListener) multiple callbacks (1 for Dog and 1 for Cat). That's why only the last event is unbind…

As it would ask some refactoring to support your use case, I will suggest using a different key as a workaround. For example, the component's name :

bind(component, ee) {
  const { name } = component;

  this.eventByElement.set(name, this.listener(component));
  document.addEventListener('click', this.eventByElement.get(name))
}

unbind(component) {
  const { name } = component;

  document.removeEventListener('click', this.eventByElement.get(name));
  this.eventByElement.delete(name);
}

Tell me if it works. Cheers!

gfnool commented 2 years ago

Perfect! Thanks a lot.