5
\$\begingroup\$

Remove an event listener after firing once or any number of times

This is what I have:

/*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
(function ()
{
    "use strict";

    function removeEventListenerAfterFiring(numberOfTimes, callback, useCapture)
    {
        var count = 0;
        return function listener(event)
        {
            count += 1;

            if (count >= numberOfTimes)
            {
                event.target.removeEventListener(event.type, listener, useCapture);
            }

            callback();
        };
    }

    function functionName()
    {
        // Code here.
    }

    window.addEventListener("DOMContentLoaded", removeEventListenerAfterFiring(1, functionName, false), false);
}());

Is there anything that could be improved, or is there a better way to do this?

Is it acceptable to specify useCapture twice? Is there a way to detect if useCapture has been specified so that I don't have to pass it to the removeEventListenerAfterFiring function?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Consider using event.currentTarget instead of event.target, since your handlers are probably bound to an ancestor element, not the current element.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.