How does one remove the bound version of an event handler?

I’ve a problem with my binding event, I would like to remove each event when change event is fired. It’s working fine without a loop.

this.objectInstance.on('selected', () => {
    document.querySelectorAll('select').forEach((el) => {
        this.test = this.fontFamilyHandler.bind(this, el.getAttribute('id'));
        el.addEventListener('change', this.test);
    }) 
});

this.objectInstance.on('deselected', () => {
    document.querySelectorAll('select').forEach((el) => {
        el.removeEventListener('change', this.test);
    })
});

fontFamilyHandler = (key, evt) => {
    this.objectInstance.set(key, evt.target.value);
    this.canvas.requestRenderAll();
}

Do you have any idea why it’s doesn’t work ?

Answer

From the above comment …

“One needs to see surrounding code in order to get an understanding of the actual this the OP is dealing with … I’m especially curious about fontFamilyHandler = (key, evt) => { /* ... */ } where this function floats freely versus line 3 where all of a sudden one sees this.fontFamilyHandler.bind(this, el.getAttribute('id'));

Until then the next provided answer assumes kind of a class syntax/system for a hypothetical MyType class.

Of cause the binding as with …

this.fontFamilyHandler.bind(this, el.getAttribute('id'));

… is not necessary at all because the OP already does access the event.target within this handler which equals the above el

fontFamilyHandler = (key, evt) => {
  this.objectInstance.set(key, evt.target.value);
  this.canvas.requestRenderAll();
}

Thus, binding each element’s id is not necessary since this property can be accessed via evt.target.id as much as the value already via evt.target.value.

In the end the code will boil down to something much more readable like …

//class MyType {
//  constructor() {
//    this.objectInstance = { on: () => {} };

    this.objectInstance.on('selected', () => document
      .querySelectorAll('select')
      .forEach(el =>
        el.addEventListener('change', this.fontFamilyHandler)
      )
    );
    this.objectInstance.on('deselected', () => document
      .querySelectorAll('select')
      .forEach(el =>
        el.removeEventListener('change', this.fontFamilyHandler)
      )
    );

    this.fontFamilyHandler = ({ target }) => {
      this.objectInstance.set(target.id, target.value);
      this.canvas.requestRenderAll();
    };

//  }
//}