Assign a method to a var?

40 views Asked by At

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();
}
1

There are 1 answers

0
rozsazoltan On

Examining the source code there is a cleanup array in the onClickOutside composable. A function called stop runs 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 stop function is void, that is, it returns nothing. Therefore, the unsubscribe variable remains an option to call the stop function 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 unsubscribe is a variable that exists for the lifetime of the application, I'd set it back to undefined for clarity.

And this way, if unsubscribe is not undefined, I wouldn't redeclare the onClickOutside call to avoid duplicates.

let unsubscribe;

async function show() {
    active.value = true;

    // avoid duplicated invocation by using ??= (so if it's not undefined, the variable assignment won't be overwritten)
    unsubscribe ??= onClickOutside(menu, () => {
        if (active.value) {
            hide();
        }
    });

    await nextTick();
    activate();
}

function hide() {
    if (unsubscribe) unsubscribe();

    // set it to undefined so that we know next time that it no longer exists
    unsubscribe = undefined;

    active.value = false;
    deactivate();
}