Design & Download
Your JS Library
in Seconds!!!

Snippet: getSimpleCallback() - Get Callbacks By Name

Written by Christopher West (cwest) on July 20, 2016.
Gets and saves YourJS functions by name while allowing for the function signature to be predetermined.
var getSimpleCallback;
(function(__callbacksByName) {
  getSimpleCallback = function (fn) {
    if (typeOf(fn, 'String')) {
      if (has(__callbacksByName, fn)) {
        fn = __callbacksByName[fn];
      }
      else {
        var func, name = fn.split(':'), indices = name[1], callbackName = fn + '';
        if (typeOf(fn = func = YourJS[name = name[0]], 'Function')) {
          if (indices != undefined) {
            indices = indices.split(',');
            fn = __callbacksByName[callbackName] = function() {
              for (var args = [], i = -1, index; index = indices[++i]; ) {
                args[i] = index == 'this' ? this : pull(arguments, index, undefined);
              }
              return func.apply(this, args);
            };
          }
        }
        else {
          throw new Error('There is no "' + name + '" function.');
        }
      }
    }
    return fn || identity;
  };
})({});

getSimpleCaller(...) API Documentation

Gets and saves YourJS functions by name while allowing for the function signature to be predetermined.

Parameters

  1. fn {Function|string}:
    If a Function is specified it will simply be returned. If a string is specified it will be used to determine the name of the YourJS function to return and it will also be determined to predetermine the signature of the function. The string should be in one of the following formats:
    • functionName:
      This will simply assure that the YourJS function with the specified function name (functionName) is returned.
    • functionName::
      This will assure that the YourJS function with the specified function name (functionName) is returned but it will not be able to receive any arguments.
    • functionName:path1,path2,...:
      This will assure that the YourJS function with the specified function name (functionName) is returned and the arguments that are received will be those found at the specified paths (path1,path2,...).

Returns

The function as indicated by the fn parameter.

Example

var slicer = YourJS.getSimpleCallback('slice:0,1.start,1.end');
console.log(slicer([3,5,7,9]));  // -> [3, 5, 7, 9]
console.log(slicer([3,5,7,9], {start: 2}));  // -> [7, 9]
console.log(slicer([3,5,7,9], {end: -1}));  // -> [3, 5, 7]