pauloabmiranda
2/12/2013 - 9:38 PM

Bocoup training: More Efficient jQuery Event Handlers

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");
  }
});