Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cowboy/4773621 to your computer and use it in GitHub Desktop.
Save cowboy/4773621 to your computer and use it in GitHub Desktop.
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");
}
});
@FWeinb
Copy link

FWeinb commented Feb 22, 2013

Great screencast! Enjoyed watching it!
I thought on how to simplify the "Event delegation + lazy evaluation" in terms of reusability and came up with this:

https://gist.github.com/FWeinb/5014324

Is this usable? Or is there even a better why of abstracting it?

@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