DylanSp
DylanSp

Reputation: 1519

How can I have Monaco's onDidChangeModelContent() function fire on every keystroke?

I'm trying to capture the value of a Monaco editor's content on every keystroke. I've tried using the editor's onDidChangeModelContent() function, but this appears to fire inconsistently, when trying it out in the playground with this code:

const editor = monaco.editor.create(document.getElementById("container"), {
    value: "function hello() {\n\talert('Hello world!');\n}",
    language: "javascript"
});

editor.onDidChangeModelContent = e => {
    console.log(editor.getValue());
};

I only see console entries when I auto-complete an Intellisense suggestion with tab, not on every keystroke. Is there another event listener I should be using, or some other technique I should try?

Upvotes: 8

Views: 4146

Answers (1)

DylanSp
DylanSp

Reputation: 1519

Figured it out; the example code was using onDidChangeModelContent() incorrectly. To set an event listener, the client code needs to call onDidChangeModelContent(), not set it. This code works:

editor.onDidChangeModelContent(e => {
    console.log(editor.getValue());
});

Upvotes: 10

Related Questions