7

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

01AutoMonkey
  • 2,515
  • 4
  • 29
  • 47

1 Answers1

16

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
})
01AutoMonkey
  • 2,515
  • 4
  • 29
  • 47