tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

component-emitter.js (1559B)


      1 /*
      2 * Event emitter component.
      3 *
      4 * Copyright (c) 2014 Component contributors <dev@component.io>
      5 *
      6 * This source code is licensed under the MIT license found in the
      7 * LICENSE file in the root directory of the library source tree.
      8 *
      9 * https://github.com/component/emitter
     10 */
     11 
     12 "use strict";
     13 
     14 /**
     15 * Initialize a new `Emitter`.
     16 *
     17 * @public
     18 */
     19 
     20 function Emitter(obj) {
     21  if (obj) {
     22    return mixin(obj);
     23  }
     24 }
     25 
     26 /**
     27 * Mixin the emitter properties.
     28 *
     29 * @param {object} obj
     30 * @return {object}
     31 * @private
     32 */
     33 
     34 function mixin(obj) {
     35  for (const key in Emitter.prototype) {
     36    obj[key] = Emitter.prototype[key];
     37  }
     38  return obj;
     39 }
     40 
     41 /**
     42 * Listen on the given `event` with `fn`.
     43 *
     44 * @param {string} event
     45 * @param {Function} fn
     46 * @return {Emitter}
     47 * @public
     48 */
     49 
     50 Emitter.prototype.on = function (event, fn) {
     51  this._callbacks = this._callbacks || {};
     52  (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
     53  return this;
     54 };
     55 
     56 /**
     57 * Emit `event` with the given args.
     58 *
     59 * @param {string} event
     60 * @param {Mixed} ...
     61 * @return {Emitter}
     62 */
     63 
     64 Emitter.prototype.emit = function (event) {
     65  this._callbacks = this._callbacks || {};
     66 
     67  const args = new Array(arguments.length - 1);
     68  let callbacks = this._callbacks["$" + event];
     69 
     70  for (let i = 1; i < arguments.length; i++) {
     71    args[i - 1] = arguments[i];
     72  }
     73 
     74  if (callbacks) {
     75    callbacks = callbacks.slice(0);
     76    for (let i = 0, len = callbacks.length; i < len; ++i) {
     77      callbacks[i].apply(this, args);
     78    }
     79  }
     80 
     81  return this;
     82 };
     83 
     84 module.exports = Emitter;