Search code examples
javascriptjqueryapieventshandler

What does the anonymous function passed into the off function mean?


What does the anonymous function passed into the off function mean?

For instance, what does the following mean:

$jqueryEl.off("click", function() { console.log("When will it be called?"); });.

Will the function() { console.log("When will it be called?"); be called once all the click listeners are removed or will it be called instead of the removed click listeners?

I am asking this since there is no clear answer to this in the documentation:

A handler function previously attached for the event(s), or the special value false.


Solution

  • What does the anonymous function passed into the off function mean?

    Nothing useful.

    Since it is a function expression, it will generate a new function. Therefore it can't have been previously attached for the event.

    It also isn't false.

    Whoever wrote that code made an error.


    Typically this happens when someone intended to conditionally remove the function:

    const myHandler = function() { console.log("When will it be called?"); };
    
    $jqueryEl.on("click", myHandler);
    
    $somethingElse.on("click", function () {
        $jqueryEl.off("click", myHandler);
    });
    

    … but when they have created two identical functions, instead of reusing the same function for the two different calls.