bindKey.js 2.0 KB

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