Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.