Removing keyboard events when custom codeblock is edited

I have a plugin that registers a custom doce block. The plugin listens for keyboard events when the user mouses over the codeblock using the code below. My problem is that if the user goes to edit the codeblock when the mouse is over the block, the event listener isn’t removed when the user exits the edit and the block is re-rendered; I end up with multiple listeners. As far as I can see, I can’t have the re-rendered listener removed becaus the callback function no longer exists.

I think that what I need is an event that tells me when the codeblock is being edited. There doesn;t seem to be such a thing, though. Any thoughts?


const root =  await el.createEl( "div", { text: "TEST" } )

const EventHandler = (event: KeyboardEvent) => {

	event.stopPropagation();
	event.preventDefault();	

	console.log( `Key Pressed:  [${event.key}]`, event )

}
const boundEventHandler = EventHandler.bind( this )

this.registerDomEvent( root, 'mouseover', ( evt: MouseEvent ) => { 
	console.log( "mousein" )
	this.registerDomEvent( document, 'keydown', boundEventHandler ) 
})
this.registerDomEvent( root, 'mouseout', ( evt: MouseEvent ) => { 
	console.log( "mouseout" )
	document.removeEventListener("keydown", boundEventHandler );
})



Maybe this could help:

I figured out that I was binding it in the registerMarkdownCodeBlockProcessor() function, so the bind function was getting overwritten every time the codeblock rendered. I created the
boundEventHandler a method of the Plugin, bound it at the start of the unload function and made the EventHandler() function a method of the Plugin and now it’s all working fine.