documentcloud/underscore — Issue #426: onceWithContext
Author: yelled3
Created: 2012-01-08 13:31:40+00:00
State: open

feature suggestion:

/**
* Returns a function that will be executed at most one time, no matter how
* often you call it. Useful for lazy initialization.
* @param func - function to call once
* @param context - the context to apply this on
* @returns function
*/
onceWithContext: function onceWithContext(func, context) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(context, arguments);
};
}

not sure if this is needed. kinda of a shorthand for

_.bind( _.once(func), context)

but I think it's more clear.