inputtextonchangecodemirroronupdate

CodeMirror 6, how to get editor value on input/update/change event?


I want the contents / value of a CodeMirror 6 editor instance to be reflected in an external variable, when the text changes the variable changes / syncs.

How to do that in CodeMirror 6?

Pseudo Code

let sync_val = "";

import {EditorView} from "@codemirror/view"
import {EditorState} from "@codemirror/state"

let myView = new EditorView({
  state: EditorState.create({doc: "hello"}),
  parent: document.body
})

myView.onChange(function(val) {
  sync_val = val;
});


Solution

  • You can use the EditorView.updateListener extension to listen for document changes:

    let sync_val = "";
    
    import {EditorView} from "@codemirror/view"
    import {EditorState} from "@codemirror/state"
    
    let myView = new EditorView({
        state: EditorState.create({
            doc: "hello",
            extensions: [
                EditorView.updateListener.of(function(e) {
                    if (e.docChanged) {
                        sync_val = e.state.doc.toString();
                    } 
                })
            ]
        }),
        parent: document.body
    })