How to detect a change of note in MarkdownView

I’m trying to figure out how to detect when the note has changed within a given MarkdownView. I’ve been using workspace.on(‘layout-change’):

this.plugin.registerEvent(
    this.app.workspace.on('layout-change', () => {
        self.createTopPanel();
    })
)

but it triggers for a wider set of events than I need. Is there another event I can use, or is there a way to somehow detect within the layout-change event that it’s a note-change within a specific view that triggered it?

Managed to work out a hack using leaf.id.

The function onMarkdownViewFileChange defined below can be used to trigger a callback whenever the note changes in a given MarkdownView.

const __onNoteChange__leafFiles = {};
const __onNoteChange__leafCallbacks = {};
let __onNoteChange__eventCreated = false;

export function onMarkdownViewFileChange(leaf: MarkdownView, callback: (oldFile: TFile, newFile: TFile) => void) {
    if (!(leaf.leaf.id in __onNoteChange__leafFiles)) {
        __onNoteChange__leafFiles[leaf.leaf.id] = leaf.file;
        __onNoteChange__leafCallbacks[leaf.leaf.id] = callback;
    }

    if (!__onNoteChange__eventCreated) {
        _obako_plugin.registerEvent(
            app.workspace.on('layout-change', () => {
                for (const leafId of Object.keys(__onNoteChange__leafFiles)) {
                    const leaf = app.workspace.getLeafById(leafId);
                    if (leaf?.view?.file?.path != __onNoteChange__leafFiles[leafId].path) {
                        __onNoteChange__leafCallbacks[leafId](__onNoteChange__leafFiles[leafId], leaf.view.file);
                        __onNoteChange__leafFiles[leafId] = leaf.view.file;
                    }
                }
            })
        )
        __onNoteChange__eventCreated = true;
    }
}

Usage:

const leaf = this.app.workspace.getActiveViewOfType(MarkdownView);

onMarkdownViewFileChange(leaf, (oldFile, newFile) => {
    console.log("Note changed")
}));

You would not want to listen to “layout-change” here - it’s for detecting the workspace’s change.

If you want to trigger a callback when the user types something in the editor, use workspace.on(“editor-change”). If you want to detect any changes to the file in the disk (including external ones), use vault.on(“modify”).