bindKey.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var baseRest = require('./_baseRest'),
  2. createWrap = require('./_createWrap'),
  3. getHolder = require('./_getHolder'),
  4. replaceHolders = require('./_replaceHolders');
  5. /** Used to compose bitmasks for function metadata. */
  6. var WRAP_BIND_FLAG = 1,
  7. WRAP_BIND_KEY_FLAG = 2,
  8. WRAP_PARTIAL_FLAG = 32;
  9. /**
  10. * Creates a function that invokes the method at `object[key]` with `partials`
  11. * prepended to the arguments it receives.
  12. *
  13. * This method differs from `_.bind` by allowing bound functions to reference
  14. * methods that may be redefined or don't yet exist. See
  15. * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
  16. * for more details.
  17. *
  18. * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
  19. * builds, may be used as a placeholder for partially applied arguments.
  20. *
  21. * @static
  22. * @memberOf _
  23. * @since 0.10.0
  24. * @category Function
  25. * @param {Object} object The object to invoke the method on.
  26. * @param {string} key The key of the method.
  27. * @param {...*} [partials] The arguments to be partially applied.
  28. * @returns {Function} Returns the new bound function.
  29. * @example
  30. *
  31. * var object = {
  32. * 'user': 'fred',
  33. * 'greet': function(greeting, punctuation) {
  34. * return greeting + ' ' + this.user + punctuation;
  35. * }
  36. * };
  37. *
  38. * var bound = _.bindKey(object, 'greet', 'hi');
  39. * bound('!');
  40. * // => 'hi fred!'
  41. *
  42. * object.greet = function(greeting, punctuation) {
  43. * return greeting + 'ya ' + this.user + punctuation;
  44. * };
  45. *
  46. * bound('!');
  47. * // => 'hiya fred!'
  48. *
  49. * // Bound with placeholders.
  50. * var bound = _.bindKey(object, 'greet', _, '!');
  51. * bound('hi');
  52. * // => 'hiya fred!'
  53. */
  54. var bindKey = baseRest(function(object, key, partials) {
  55. var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
  56. if (partials.length) {
  57. var holders = replaceHolders(partials, getHolder(bindKey));
  58. bitmask |= WRAP_PARTIAL_FLAG;
  59. }
  60. return createWrap(key, bitmask, object, partials, holders);
  61. });
  62. // Assign default placeholders.
  63. bindKey.placeholder = {};
  64. module.exports = bindKey;