event_emitter.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*!
  2. * lunr.EventEmitter
  3. * Copyright (C) @YEAR Oliver Nightingale
  4. */
  5. /**
  6. * lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers and triggering events and their handlers.
  7. *
  8. * @constructor
  9. */
  10. lunr.EventEmitter = function () {
  11. this.events = {}
  12. }
  13. /**
  14. * Binds a handler function to a specific event(s).
  15. *
  16. * Can bind a single function to many different events in one call.
  17. *
  18. * @param {String} [eventName] The name(s) of events to bind this function to.
  19. * @param {Function} fn The function to call when an event is fired.
  20. * @memberOf EventEmitter
  21. */
  22. lunr.EventEmitter.prototype.addListener = function () {
  23. var args = Array.prototype.slice.call(arguments),
  24. fn = args.pop(),
  25. names = args
  26. if (typeof fn !== "function") throw new TypeError ("last argument must be a function")
  27. names.forEach(function (name) {
  28. if (!this.hasHandler(name)) this.events[name] = []
  29. this.events[name].push(fn)
  30. }, this)
  31. }
  32. /**
  33. * Removes a handler function from a specific event.
  34. *
  35. * @param {String} eventName The name of the event to remove this function from.
  36. * @param {Function} fn The function to remove from an event.
  37. * @memberOf EventEmitter
  38. */
  39. lunr.EventEmitter.prototype.removeListener = function (name, fn) {
  40. if (!this.hasHandler(name)) return
  41. var fnIndex = this.events[name].indexOf(fn)
  42. this.events[name].splice(fnIndex, 1)
  43. if (!this.events[name].length) delete this.events[name]
  44. }
  45. /**
  46. * Calls all functions bound to the given event.
  47. *
  48. * Additional data can be passed to the event handler as arguments to `emit`
  49. * after the event name.
  50. *
  51. * @param {String} eventName The name of the event to emit.
  52. * @memberOf EventEmitter
  53. */
  54. lunr.EventEmitter.prototype.emit = function (name) {
  55. if (!this.hasHandler(name)) return
  56. var args = Array.prototype.slice.call(arguments, 1)
  57. this.events[name].forEach(function (fn) {
  58. fn.apply(undefined, args)
  59. })
  60. }
  61. /**
  62. * Checks whether a handler has ever been stored against an event.
  63. *
  64. * @param {String} eventName The name of the event to check.
  65. * @private
  66. * @memberOf EventEmitter
  67. */
  68. lunr.EventEmitter.prototype.hasHandler = function (name) {
  69. return name in this.events
  70. }