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