Destructor when removing extension from compartment

I’m encountering issues with using CodeMirror in React, due to React’s double-rendering in (strict) development mode. I’ve partly solved this by placing my extensions in Compartments and re-configuring them.

However, now I’m having the issue that my extension is adding an event listener, but doesn’t remove it when the extension gets reconfigured. I see there is a destroy() option, but it seems like that only gets called when the view gets destroyed.

My code looks roughly like this:

const compartment = new Compartment();

const extension = ViewPlugin.fromClass(
  class {
    constructor(view) {
      this.handler = () => { /* ... */ };
      // how to remove this event listener when the extension gets reconfigured?
      view.scrollDOM.addEventListener("scroll", this.handler);
    }

    destroy() {
      console.log("this is not being called :(");
      view.scrollDOM.removeEventListener("scroll", this.handler);
    }
  },
);

function Component() {
  // ...
  useEffect(() => {
    console.log("this will run twice in development");
    view.dispatch({
      effects: compartment.reconfigure(extension),
    });
  }, [compartment, view]);
  // ...
}

How can I remove the event listener?

destroy should also get called when a plugin is removed from the editor’s configuration.

1 Like

Thanks for confirming—upon further inspection, I found the bug elsewhere in my code.