简体   繁体   中英

How do I add and remove an event listener using a function with event argument and parameters?

For example, I have below function to execute when mouseup event occurs.

const listener = (element: HTMLElement, e: MouseEvent): void => {
    if (e.target instanceof Element && element && !element.contains(e.target)) {
        element.style.backgroundColor = 'red';
    }
}

Then I am trying to figure out how to add extra paramter element to listener and remove it when it is not required anymore.

function addEventListener (element: HTMLElement) => {
    window.document.addEventListener('mouseup', (e) => listener(element, e));
}

function removeEventListener (element: HTMLElement) => {
    window.document.removeEventListener('mouseup', ?? );
}

How can I solve this problem?

I tried using bind like below, but MouseEvent cannot bind before addEventListener .

let callback;

function addEventListener (element: HTMLElement) => {
    // how can I bind `MouseEvent`?
    callback = listener.bind(this, element, ??);
    window.document.addEventListener('mouseup', callback);
}

function removeEventListener (element: HTMLElement) => {
    window.document.removeEventListener('mouseup', callback);
}

Should I use closure here like below?

function createListener(element: HTMLElement) {
    return (e: MouseEvent) => {
        listener(element, e);
    }
}

let callback;

function addEventListener (element: HTMLElement) {
    callback = createListener(account);
    window.document.addEventListener('mouseup', callback);
}

function removeEventListener (element: HTMLElement) => {
    window.document.removeEventListener('mouseup', callback);
}

The same way you remove an event listener normally, but store an object (dictionary) that maps an HTMLElement to a function:

interface Callbacks {
    [key: HTMLElement]: (e: MouseEvent) => void
}

let callbacks: Callbacks = {};

function addEventListener (element: HTMLElement) => {
    callbacks[element] = (e) => listener(element, e);
    window.document.addEventListener('mouseup', callback);
}

function removeEventListener (element: HTMLElement) => {
    window.document.removeEventListener('mouseup', callbacks[element]);
    delete callbacks[element];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM