This commit is contained in:
Jeremy Ashkenas
2011-03-20 19:26:52 -04:00
2 changed files with 20 additions and 0 deletions

View File

@@ -108,6 +108,15 @@ $(document).ready(function() {
_.delay(function(){ ok(counter == 1, "incr was debounced"); start(); }, 220); _.delay(function(){ ok(counter == 1, "incr was debounced"); start(); }, 220);
}); });
test("functions: once", function() {
var addBang = function(str) { return str + "!"; };
hi = "Hi";
hi2 = _.once(addBang, hi);
hi3 = _.once(addBang, hi);
equals(hi2, "Hi!");
equals(hi3, undefined);
});
test("functions: wrap", function() { test("functions: wrap", function() {
var greet = function(name){ return "hi: " + name; }; var greet = function(name){ return "hi: " + name; };
var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); }); var backwards = _.wrap(greet, function(func, name){ return func(name) + ' ' + name.split('').reverse().join(''); });

View File

@@ -475,6 +475,17 @@
return limit(func, wait, true); return limit(func, wait, true);
}; };
// Runs a function only if it's never been run before.
_.once = function(func) {
if (_.indexOf(onceRunFunctions, func)) {
onceRunFunctions.push(func);
return func.apply(func, slice.call(arguments, 1));
}
}
// 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
// conditionally execute the original function. // conditionally execute the original function.