bindAll.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var arrayEach = require('./_arrayEach'),
  2. baseAssignValue = require('./_baseAssignValue'),
  3. bind = require('./bind'),
  4. flatRest = require('./_flatRest'),
  5. toKey = require('./_toKey');
  6. /**
  7. * Binds methods of an object to the object itself, overwriting the existing
  8. * method.
  9. *
  10. * **Note:** This method doesn't set the "length" property of bound functions.
  11. *
  12. * @static
  13. * @since 0.1.0
  14. * @memberOf _
  15. * @category Util
  16. * @param {Object} object The object to bind and assign the bound methods to.
  17. * @param {...(string|string[])} methodNames The object method names to bind.
  18. * @returns {Object} Returns `object`.
  19. * @example
  20. *
  21. * var view = {
  22. * 'label': 'docs',
  23. * 'click': function() {
  24. * console.log('clicked ' + this.label);
  25. * }
  26. * };
  27. *
  28. * _.bindAll(view, ['click']);
  29. * jQuery(element).on('click', view.click);
  30. * // => Logs 'clicked docs' when clicked.
  31. */
  32. var bindAll = flatRest(function(object, methodNames) {
  33. arrayEach(methodNames, function(key) {
  34. key = toKey(key);
  35. baseAssignValue(object, key, bind(object[key], object));
  36. });
  37. return object;
  38. });
  39. module.exports = bindAll;