diff options
Diffstat (limited to 'lib/scripts/helpers.js')
-rw-r--r-- | lib/scripts/helpers.js | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/scripts/helpers.js b/lib/scripts/helpers.js index 77e7ffc4a..b286965cf 100644 --- a/lib/scripts/helpers.js +++ b/lib/scripts/helpers.js @@ -163,3 +163,32 @@ function substr_replace(str, replace, start, length) { b1 = (length < 0 ? str.length : a2) + length; return str.substring(0, a2) + replace + str.substring(b1); } + +/** + * Bind variables to a function call creating a closure + * + * Use this to circumvent variable scope problems when creating closures + * inside a loop + * + * @author Adrian Lang <lang@cosmocode.de> + * @link http://www.cosmocode.de/en/blog/gohr/2009-10/15-javascript-fixing-the-closure-scope-in-loops + * @param functionref fnc - the function to be called + * @param mixed - any arguments to be passed to the function + * @returns functionref + */ +function bind(fnc/*, ... */) { + var Aps = Array.prototype.slice; + // Store passed arguments in this scope. + // Since arguments is no Array nor has an own slice method, + // we have to apply the slice method from the Array.prototype + var static_args = Aps.call(arguments, 1); + + // Return a function evaluating the passed function with the + // given args and optional arguments passed on invocation. + return function (/* ... */) { + // Same here, but we use Array.prototype.slice solely for + // converting arguments to an Array. + return fnc.apply(this, + static_args.concat(Aps.call(arguments, 0))); + }; +} |