Last active
March 25, 2021 03:53
-
-
Save FWeinb/5014324 to your computer and use it in GitHub Desktop.
Simple lazy evaluation pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
$.fn.cache = function (key, create, use){ | |
var data = this.data(key); | |
if (!data){ | |
data = create(); | |
this.data(key, data); | |
} | |
return use(data); | |
}; | |
})(jQuery); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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