6
\$\begingroup\$

I have a notification system that looks like this:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').click(function () {
        unBlockScreen();
        $(this).off("click"); // once they click the "Okay" button, remove the click event
    });
}

The reason that I'm putting the .click() handler in the notificationMethod() as opposed to the $(document).ready() is to be able to keep the notification code separate from the rest of the code that it has nothing to do with (other than it's on the same page). However, looking at my code it feels odd to have the .off("click") inside of the .click().

Is there anything particularly wrong with this approach?

\$\endgroup\$
10
\$\begingroup\$

For a handler that only fires once using jQuery you can use .one().

A click handler would look something like:

function notificationMethod(message){
    // do stuff

    // once everything else is setup, attach a click handler to the "Okay" button
    $('#notificationOkay').one("click", unBlockScreen);
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Huh, +2 if I could. \$\endgroup\$ – konijn Mar 25 '14 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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