Is it ok to use closed values for keeping track of custom extension states?

Consider this simple plugin, which uses closed values to store a mouse position to access inside the keydown event.

From the docs it looks like it’s recommended to use StateField, StateEffects and transactions to manage states (plz correct me if I’m wrong), but that looks like a lot of work, curious if this approach below is OK here, and if there’s any caveat?

const myExtension = () => {

	let mouseX = 0;
	let mouseY = 0;

	return EditorView.domEventHandlers({
		mousemove: (e, view) => {
			mouseX = e.clientX;
			mouseY = e.clientY;
		},
		keydown: (e, view) => {
			const pos = view.posAtCoords({ mouseX, mouseY });
			// do whatever
		},
	});

};

For things like this, mutable fields in a view plugin would be more appropriate than state fields. Closing over stuff works too, as long as you’re careful not to use the same extension in multiple views.

1 Like

Thanks for the fast response!

I wasn’t aware you can easily access view plugin value in event handlers through this or view.plugin(), this is easy and definitely safer. Thank you!