83 lines
2.2 KiB
JavaScript
83 lines
2.2 KiB
JavaScript
|
/*!
|
||
|
* lunr.EventEmitter
|
||
|
* Copyright (C) @YEAR Oliver Nightingale
|
||
|
*/
|
||
|
|
||
|
/**
|
||
|
* lunr.EventEmitter is an event emitter for lunr. It manages adding and removing event handlers and triggering events and their handlers.
|
||
|
*
|
||
|
* @constructor
|
||
|
*/
|
||
|
lunr.EventEmitter = function () {
|
||
|
this.events = {}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Binds a handler function to a specific event(s).
|
||
|
*
|
||
|
* Can bind a single function to many different events in one call.
|
||
|
*
|
||
|
* @param {String} [eventName] The name(s) of events to bind this function to.
|
||
|
* @param {Function} fn The function to call when an event is fired.
|
||
|
* @memberOf EventEmitter
|
||
|
*/
|
||
|
lunr.EventEmitter.prototype.addListener = function () {
|
||
|
var args = Array.prototype.slice.call(arguments),
|
||
|
fn = args.pop(),
|
||
|
names = args
|
||
|
|
||
|
if (typeof fn !== "function") throw new TypeError ("last argument must be a function")
|
||
|
|
||
|
names.forEach(function (name) {
|
||
|
if (!this.hasHandler(name)) this.events[name] = []
|
||
|
this.events[name].push(fn)
|
||
|
}, this)
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Removes a handler function from a specific event.
|
||
|
*
|
||
|
* @param {String} eventName The name of the event to remove this function from.
|
||
|
* @param {Function} fn The function to remove from an event.
|
||
|
* @memberOf EventEmitter
|
||
|
*/
|
||
|
lunr.EventEmitter.prototype.removeListener = function (name, fn) {
|
||
|
if (!this.hasHandler(name)) return
|
||
|
|
||
|
var fnIndex = this.events[name].indexOf(fn)
|
||
|
this.events[name].splice(fnIndex, 1)
|
||
|
|
||
|
if (!this.events[name].length) delete this.events[name]
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Calls all functions bound to the given event.
|
||
|
*
|
||
|
* Additional data can be passed to the event handler as arguments to `emit`
|
||
|
* after the event name.
|
||
|
*
|
||
|
* @param {String} eventName The name of the event to emit.
|
||
|
* @memberOf EventEmitter
|
||
|
*/
|
||
|
lunr.EventEmitter.prototype.emit = function (name) {
|
||
|
if (!this.hasHandler(name)) return
|
||
|
|
||
|
var args = Array.prototype.slice.call(arguments, 1)
|
||
|
|
||
|
this.events[name].forEach(function (fn) {
|
||
|
fn.apply(undefined, args)
|
||
|
})
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Checks whether a handler has ever been stored against an event.
|
||
|
*
|
||
|
* @param {String} eventName The name of the event to check.
|
||
|
* @private
|
||
|
* @memberOf EventEmitter
|
||
|
*/
|
||
|
lunr.EventEmitter.prototype.hasHandler = function (name) {
|
||
|
return name in this.events
|
||
|
}
|
||
|
|