Closed pjeby closed 3 years ago
You are right actually, event handlers are never removed.
I will do as you suggested register during onload
and remove onunload
, however, can you maybe advise how to read the data-path
attribute within the snippet below:
document.on(
'contextmenu',
`div.CodeMirror-linewidget.oz-image-widget > img[data-path]`,
(e) => {
...
}
)
Use (event, target) =>
as the signature; target will be the img element, so I believe you should be able to use target.dataset.path
to get the file path, and from there use vault.getAbstractFileByPath()
to retrieve the file.
You need to save the callback, though, or make it a method of the plugin, because for document.off()
you need to pass the exact same parameters, including a fourth parameter that should be a boolean (the capture mode). So e.g. something like:
export default class ... extends Plugin {
onImageMenu = (event: MouseEvent, target: HTMLElement) => {
const file = this.app.vault.getAbstractFileByPath(target.dataset.path);
if (!file instanceof TFile) return;
// .... menu setup here
event.preventDefault();
event.stopPropagation();
return false;
}
onload() {
...
document.on('contextmenu', `div.CodeMirror-linewidget.oz-image-widget > img[data-path]`, this.onImageMenu, false);
}
onunload() {
...
document.off('contextmenu', `div.CodeMirror-linewidget.oz-image-widget > img[data-path]`, this.onImageMenu, false);
}
}
Thanks a lot for your input! I just changed removed the existing event handler and implemented as the way you suggested. Hopefully, it should be ok now 🙂
Nice! Thanks.
If I understand the code correctly, it is adding a new event handler for each instance of a local file image, in every pane. These event handlers are then never removed, even if the plugin is unloaded.
Rather than register a handler for each file, why not register the handler once at startup (and remove it with
document.off
in onunload), and have it match[data-path]
without a specific path. The handler could then look up the file object using the path, so a new handler would not be needed for each image in each open pane.