patternjavascriptModerate
Better alternative to $(this).off("click")
Viewed 0 times
thisclickalternativebetteroff
Problem
I have a notification system that looks like this:
The reason that I'm putting the
Is there anything particularly wrong with this approach?
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?
Solution
For a handler that only fires once using jQuery you can use .one().
A click handler would look something like:
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);
}Code Snippets
function notificationMethod(message){
// do stuff
// once everything else is setup, attach a click handler to the "Okay" button
$('#notificationOkay').one("click", unBlockScreen);
}Context
StackExchange Code Review Q#45269, answer score: 10
Revisions (0)
No revisions yet.