Skip to content

Instantly share code, notes, and snippets.

@FWeinb
Last active March 25, 2021 03:53
Show Gist options
  • Save FWeinb/5014324 to your computer and use it in GitHub Desktop.
Save FWeinb/5014324 to your computer and use it in GitHub Desktop.
Simple lazy evaluation pattern
(function($){
$.fn.cache = function (key, create, use){
var data = this.data(key);
if (!data){
data = create();
this.data(key, data);
}
return use(data);
};
})(jQuery);
/*
* Sample based on:
* bocoup-training-more-efficient-event-handlers.js https://gist.github.com/cowboy/4773621
*
*/
$("form").on("click", "button", function(event) {
event.preventDefault();
var button = $(this);
button.cache(
"countdown",
function(){
data = {};
data.numberElem = button.find(".number");
data.number = Number(data.numberElem.text());
button.data("countdown", data);
return data;
},
function(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