mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-11 11:27:50 +00:00
Adding _.once ... Issue #121
This commit is contained in:
@@ -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() {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user