elasticlunr

EventEmitter

constructor
elasticlunr.EventEmitter()

elasticlunr.EventEmitter is an event emitter for elasticlunr.
It manages adding and removing event handlers and triggering events and their handlers.

Each event could has multiple corresponding functions,
these functions will be called as the sequence that they are added into the event.

elasticlunr.EventEmitter = function () {
  this.events = {};
};

addListener

method
elasticlunr.EventEmitter.prototype.addListener()

Option name Type Description
[eventName] String

The name(s) of events to bind this function to.

fn Function

The function to call when an event is fired.

Binds a handler function to a specific event(s).

Can bind a single function to many different events in one call.

elasticlunr.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);
};

removeListener

method
elasticlunr.EventEmitter.prototype.removeListener()

Option name Type Description
eventName String

The name of the event to remove this function from.

fn Function

The function to remove from an event.

Removes a handler function from a specific event.

elasticlunr.EventEmitter.prototype.removeListener = function (name, fn) {
  if (!this.hasHandler(name)) return;

  var fnIndex = this.events[name].indexOf(fn);
  if (fnIndex === -1) return;

  this.events[name].splice(fnIndex, 1);

  if (this.events[name].length == 0) delete this.events[name];
};

emit

method
elasticlunr.EventEmitter.prototype.emit()

Option name Type Description
eventName String

The name of the event to emit.

Call all functions that bounded to the given event.

Additional data can be passed to the event handler as arguments to emit
after the event name.

elasticlunr.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);
  }, this);
};