CodeMirror 6: Proper way to listen for changes

I read your conversation and decided to use a ViewPlugin. When reading the documentation I struggled a bit to figure out that a plugin can be added as an extension.
I came up with the following solution to watch the editor:

initEditor() {
	const compThis = this //save this context
	const editor = new EditorView({
        state: EditorState.create({
          doc: 'Loading the real content',
          extensions: [
            ViewPlugin.fromClass(class {
              constructor(view) {}

              update(update) {
                if (update.docChanged)
                  compThis.onDocumentChanged() //escort the update event up one level. This function saves the contents and interact with the other UI.
              }
            }),
            lineNumbers(),
            highlightSpecialChars(),
            history(),
            foldGutter(),
            multipleSelections(),
            defaultHighlighter,
            bracketMatching(),
            closeBrackets(),
            autocomplete(),
            rectangularSelection(),
            highlightActiveLine(),
            highlightSelectionMatches(),
            keymap([
              ...defaultKeymap,
              ...searchKeymap,
              ...historyKeymap,
              ...foldKeymap,
              ...commentKeymap,
              ...gotoLineKeymap,
              ...autocompleteKeymap,
              ...lintKeymap
            ])
          ]
        })
	this.$refs.editor.append(this.editorView.dom)
	//other init stuff
}

I doubt that this is used in the way its intended to be used? Is there a better way to do this? How can I pass information down to my plugin?

1 Like