Adding _.once ... Issue #121

This commit is contained in:
Jeremy Ashkenas
2011-03-20 19:32:20 -04:00
parent 52916aad87
commit 39119065dc
2 changed files with 16 additions and 17 deletions

View File

@@ -109,12 +109,11 @@ $(document).ready(function() {
}); });
test("functions: once", function() { test("functions: once", function() {
var addBang = function(str) { return str + "!"; }; var num = 0;
hi = "Hi"; var increment = _.once(function(){ num++; });
hi2 = _.once(addBang, hi); increment();
hi3 = _.once(addBang, hi); increment();
equals(hi2, "Hi!"); equals(num, 1);
equals(hi3, undefined);
}); });
test("functions: wrap", function() { test("functions: wrap", function() {

View File

@@ -475,16 +475,16 @@
return limit(func, wait, true); return limit(func, wait, true);
}; };
// Runs a function only if it's never been run before. // Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) { _.once = function(func) {
if (_.indexOf(onceRunFunctions, func)) { var ran = false, memo;
onceRunFunctions.push(func); return function() {
return func.apply(func, slice.call(arguments, 1)); if (ran) return memo;
} ran = true;
} return memo = func.apply(this, arguments);
};
// Internal record of functions that have been run via `_.once`. };
var onceRunFunctions = [];
// Returns the first function passed as an argument to the second, // Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and // allowing you to adjust arguments, run code before and after, and