A
A
andrey_chirkin2022-02-01 11:35:07
JavaScript
andrey_chirkin, 2022-02-01 11:35:07

How can an event handler be removed if a function with arguments is passed as an argument to addEventListener?

Good afternoon! I have such a problem, I need to pass an argument to the event handler. But then, with another event, you need to remove this handler. Can't figure out how to do it. Example:

const but1 = useRef(null)
    const but2 = useRef(null)

    const handleButtonMove = () => (
        (event) => {
            console.log(event.target)
        }
    )


    const handleButtonClick = (elBut1) => (
        (event) => {
            elBut1.removeEventListener("mousemove", handleButtonMove())
        }
    )

    useEffect(() => {
        const elBut1 = but1.current
        const elBut2 = but2.current
        elBut1.addEventListener("mousemove", handleButtonMove())
        elBut2.addEventListener("click", handleButtonClick(elBut1))
    }, [])

return (
        <div className="operationTable">
            <button ref={but1}>Button 1</button>
            <button ref={but2}>Button 1</button>
        </div>
    )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@insighter, 2022-02-01
@andrey_chirkin

const handleButtonClick = (elBut1) => (
        (event) => {
            elBut1.removeEventListener("mousemove", handleButtonMove())
        }
    )

const handleElBut1Click = handleButtonClick(elBut1);

elBut2.addEventListener("click", handleElBut1Click)
elBut2.removeEventListener("click", handleElBut1Click)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question