Last active
August 29, 2015 14:04
-
-
Save dmikey/600ebf57cc11e085d13c to your computer and use it in GitHub Desktop.
Gives Enyo the ability to generate functions that can only be executed ONE time, regardless of how many times it is called.
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(enyo, scope){ | |
/** | |
* _enyo.Once_ returns a function that will only be executed one time no matter | |
* how many times it was called. | |
* | |
* borrowed from underscore | |
* | |
* @class enyo.Once | |
* @public | |
*/ | |
//shortcuts | |
var ArrayProto = Array.prototype; | |
var slice = ArrayProto.slice; | |
/** | |
* returns a function that will be executed before N times. | |
* | |
* @method | |
* @type {Function} | |
* @private | |
*/ | |
var before = function(times, func) { | |
var memo; | |
return function() { | |
if (--times > 0) { | |
memo = func.apply(this, arguments); | |
} | |
else func = null; | |
return memo; | |
}; | |
}; | |
/** | |
* returns a partially applied function, without changing it's 'this' context | |
* | |
* @method | |
* @type {Function} | |
* @private | |
*/ | |
var partial = function(func) { | |
var boundArgs = slice.call(arguments, 1); | |
return function() { | |
var position = 0; | |
var args = boundArgs.slice(); | |
for (var i = 0, length = args.length; i < length; i++) { | |
if (args[i] === enyo) args[i] = arguments[position++]; | |
} | |
while (position < arguments.length) args.push(arguments[position++]); | |
return func.apply(this, args); | |
}; | |
}; | |
/** | |
* Returns a function that will only be executed once reguardless of how many times it is called. | |
* | |
* @method | |
* @type {Function} | |
* @public | |
*/ | |
enyo.Once = enyo.Once || partial(before, 2); | |
}(enyo, this)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment