Webpack-hot-middleware multiplies event listeners

531 Views Asked by At

While trying to set up my new development environment (node server + client with only vanilla js on board), I faced with webpack-hot-middleware for hot reloading my front-end changes. And everything would be fine, but if there are any code like this

$button.addEventListener('click', () => {
  // any code here
});

than after hot reloading, when you click on $button, this event listener will fire one more time than before! Terribly uncomfortable, but I did not found any reports of a similar problem from anyone. Can anyone help me with possible workarounds of this problem?

1

There are 1 best solutions below

0
On

I recommend reading the webpack hot module replacement documentation, which describes how to handle issues like this.

Basically, when your code changes you'll need to update the event binding using module.hot.accept with something like this.

if (module.hot) {
  module.hot.accept('./yourCode.js', function() {
    console.log('Accepting the updated yourCode module!');

    $button.removeEventListener('click', oldHandler);
    $button.addEventListener('click', newHandler);
  })
}

The tricky bit will be clearing event listeners properly, since you'll need to have a reference to the original handler or you'll need to clear all handlers.