Forked from cowboy/bocoup-training-more-efficient-event-handlers.js
Created
February 15, 2013 16:24
-
-
Save flexbox/4961475 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Straightforward + simple. | |
$("button").on("click", function(event) { | |
event.preventDefault(); | |
var button = $(this); | |
var numberElem = button.find(".number"); | |
var number = Number(numberElem.text()) - 1; | |
numberElem.text(number); | |
if (number === 0) { | |
button.prop("disabled", true); | |
button.off("click"); | |
} | |
}); | |
// Naive optimization. Too much work done up-front. | |
$("button").each(function() { | |
var button = $(this); | |
var numberElem = button.find(".number"); | |
var number = Number(numberElem.text()); | |
button.on("click", function(event) { | |
event.preventDefault(); | |
number = number - 1; | |
numberElem.text(number); | |
if (number === 0) { | |
button.prop("disabled", true); | |
button.off("click"); | |
} | |
}); | |
}); | |
// Lazy evaluation. | |
$("button").each(function() { | |
var button = $(this); | |
var numberElem, number; | |
button.on("click", function(event) { | |
if (!numberElem) { | |
numberElem = button.find(".number"); | |
number = Number(numberElem.text()); | |
} | |
event.preventDefault(); | |
number = number - 1; | |
numberElem.text(number); | |
if (number === 0) { | |
button.prop("disabled", true); | |
button.off("click"); | |
} | |
}); | |
}); | |
// Event delegation style | |
$("form").on("click", "button", function(event) { | |
event.preventDefault(); | |
var button = $(this); | |
var numberElem = button.find(".number"); | |
var number = Number(numberElem.text()) - 1; | |
numberElem.text(number); | |
if (number === 0) { | |
button.prop("disabled", true); | |
} | |
}); | |
// Event delegation + lazy evaluation | |
$("form").on("click", "button", function(event) { | |
event.preventDefault(); | |
var button = $(this); | |
var data = button.data("countdown"); | |
if (!data) { | |
data = {}; | |
data.numberElem = button.find(".number"); | |
data.number = Number(data.numberElem.text()); | |
button.data("countdown", data); | |
} | |
data.number = data.number - 1; | |
data.numberElem.text(data.number); | |
if (data.number === 0) { | |
button.prop("disabled", true); | |
button.removeData("countdown"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment