bindAll.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var baseFlatten = require('../internal/baseFlatten'),
  2. createWrapper = require('../internal/createWrapper'),
  3. functions = require('../object/functions'),
  4. restParam = require('./restParam');
  5. /** Used to compose bitmasks for wrapper metadata. */
  6. var BIND_FLAG = 1;
  7. /**
  8. * Binds methods of an object to the object itself, overwriting the existing
  9. * method. Method names may be specified as individual arguments or as arrays
  10. * of method names. If no method names are provided all enumerable function
  11. * properties, own and inherited, of `object` are bound.
  12. *
  13. * **Note:** This method does not set the "length" property of bound functions.
  14. *
  15. * @static
  16. * @memberOf _
  17. * @category Function
  18. * @param {Object} object The object to bind and assign the bound methods to.
  19. * @param {...(string|string[])} [methodNames] The object method names to bind,
  20. * specified as individual method names or arrays of method names.
  21. * @returns {Object} Returns `object`.
  22. * @example
  23. *
  24. * var view = {
  25. * 'label': 'docs',
  26. * 'onClick': function() {
  27. * console.log('clicked ' + this.label);
  28. * }
  29. * };
  30. *
  31. * _.bindAll(view);
  32. * jQuery('#docs').on('click', view.onClick);
  33. * // => logs 'clicked docs' when the element is clicked
  34. */
  35. var bindAll = restParam(function(object, methodNames) {
  36. methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
  37. var index = -1,
  38. length = methodNames.length;
  39. while (++index < length) {
  40. var key = methodNames[index];
  41. object[key] = createWrapper(object[key], BIND_FLAG, object);
  42. }
  43. return object;
  44. });
  45. module.exports = bindAll;