Skip to content

Instantly share code, notes, and snippets.

  • Star 27 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Bocoup training: More Efficient jQuery Event Handlers
// 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");
}
});
@thejsj
Copy link

thejsj commented Sep 23, 2013

Great screencast! Simple and useful!

I do have a question thought: Isn't button.data also manipulating the DOM... in that case, isn't it quite similar to .find('number'). Aren't they both searching for something in the DOM anyway?

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment