I set an event listener when my nav is shown in show, this is via onClickOutside from VueUse.
I assign the returned method from onClickOutside to a var, calling this later turns off the event listener.
My question is, how can I assign the click handler in show and unassign in hide?
Do I need to set the unsubscribe var somewhere else?
async function show() {
active.value = true;
unsubscribe = onClickOutside(menu, () => {
if (active.value) {
hide();
}
});
await nextTick();
activate();
}
function hide() {
unsubscribe();
active.value = false;
deactivate();
}
Examining the source code there is a
cleanuparray in theonClickOutsidecomposable. A function calledstopruns on each element of the array and stops the events. This is returned by the system when the student is created. So to stop you simply call the function.It is clear from the source code that the return type of the
stopfunction isvoid, that is, it returns nothing. Therefore, theunsubscribevariable remains an option to call thestopfunction again, which is now meaningless.You didn't share the full source code, so if it's within the scope of a function, it's understandable. However, if
unsubscribeis a variable that exists for the lifetime of the application, I'd set it back toundefinedfor clarity.And this way, if
unsubscribeis notundefined, I wouldn't redeclare theonClickOutsidecall to avoid duplicates.