How to cleanup custom NodeView with vanilla javascript #6895
-
The addNodeView() {
return ({ editor, node, getPos }) => {
const { view } = editor
// Create a button …
const button = document.createElement('button')
button.innerHTML = `This button has been clicked ${node.attrs.count} times.`
// … and when it’s clicked …
button.addEventListener('click', () => {
if (typeof getPos === 'function') {
// … dispatch a transaction, for the current position in the document …
view.dispatch(view.state.tr.setNodeMarkup(getPos(), undefined, {
count: node.attrs.count + 1,
}))
// … and set the focus back to the editor.
editor.commands.focus()
}
})
// …
}
} I understand that this sample can register event listeners to the DOM, but I didn't know how to remove them. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @tt4g, I'm pretty sure the way to go is to use the I haven't spun this up myself to test it, but it should totally work. Maybe you can give this a shot? addNodeView() {
return ({ editor, node, getPos }) => {
const { view } = editor;
const button = document.createElement('button');
button.innerHTML = `This button has been clicked ${node.attrs.count} times.`;
// define the handler so you can remove it later
const handleClick = () => {
if (typeof getPos === 'function') {
view.dispatch(view.state.tr.setNodeMarkup(getPos(), undefined, {
count: node.attrs.count + 1,
}));
editor.commands.focus();
}
};
button.addEventListener('click', handleClick);
return {
dom: button,
destroy: () => {
// cleanup!
button.removeEventListener('click', handleClick);
console.log('NodeView destroyed, listener removed.');
},
};
};
} Let us know if that works for ya |
Beta Was this translation helpful? Give feedback.
Hi @tt4g,
I'm pretty sure the way to go is to use the
destroy
method on the NodeView object you return. Tiptap just uses the standard ProseMirror NodeView interface under the hood, and that has adestroy
hook for exactly this kind of cleanup.I haven't spun this up myself to test it, but it should totally work. Maybe you can give this a shot?