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

4.9k Views Asked by At

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;
});

1

There are 1 best solutions below

0
On BEST ANSWER

The following works (use the updateListener extension):

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) {
                sync_val = e.state.doc.toString();
            })
        ]
    }),
    parent: document.body
})