Listen to Change Event

Hello and sorry for asking such a basic question. I may be just misunderstanding this new structure where everything is an object/module. I have used code mirror 5 for a long time and am now migrating to v6

In CodeMirror 5, I would subscribe to change events like so

editor.on('change', (args) => { doStuff() } )

In CodeMirror 6, I have something like this:

EditorView.updateListener.of((v: ViewUpdate) => {
  // Do something
})

But this fires on every key press. Thus I’m checking for focusChanged as a workaround. Is there a more direct way to just listen for the native change event?

If you are only interested in updates that change the document, check v.docChanged in your handler.

3 Likes

Hey thanks for taking the time to reply.

I’m going to go with another approach to solve what I want to achieve so no worries on this but just wanted to clarify.

When I say change event I mean the native html change event: HTMLElement: change event - Web APIs | MDN

docChanged fires after a keyup. So not exactly what I’m looking for.

Ah, I see. DOM event handlers are registered with EditorView.domEventHandlers.

1 Like

Where can I find a working example of how to use domEventHandlers? Listening to change event is a pretty basic thing and I have spent hours trying to figure this out.

Where can I find a working example of how to use domEventHandlers?

This should be a working example:

import {basicSetup, EditorView} from "codemirror"
import {javascript} from "@codemirror/lang-javascript"

new EditorView({
  doc: "console.log('hello')\n",
  extensions: [
    basicSetup, javascript(),
    EditorView.domEventHandlers({
        scroll: () => alert('scroll'),
        focus: () => alert('focus'),
        paste: event => alert('paste ' + event),
    }),
  ],
  parent: document.body
})

1 Like

This does not work for change event.

That’s not a DOM event that ever fires for contenteditable elements.

OK, so back to original question: how do I track changes to content?

Go back to the very first two posts in the topic and you’ll know.