How to use the events.prototype function in events

To help you get started, we’ve selected a few events examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github graalvm / graaljs / test / parallel / test-event-emitter-get-max-listeners.js View on Github external
const EventEmitter = require('events');

const emitter = new EventEmitter();

assert.strictEqual(emitter.getMaxListeners(), EventEmitter.defaultMaxListeners);

emitter.setMaxListeners(0);
assert.strictEqual(emitter.getMaxListeners(), 0);

emitter.setMaxListeners(3);
assert.strictEqual(emitter.getMaxListeners(), 3);

// https://github.com/nodejs/node/issues/523 - second call should not throw.
const recv = {};
EventEmitter.prototype.on.call(recv, 'event', () => {});
EventEmitter.prototype.on.call(recv, 'event', () => {});
github graalvm / graaljs / lib / internal / worker / io.js View on Github external
STDIO_PAYLOAD: 'stdioPayload',
  STDIO_WANTS_MORE_DATA: 'stdioWantsMoreData',
  LOAD_SCRIPT: 'loadScript'
};

// We have to mess with the MessagePort prototype a bit, so that a) we can make
// it inherit from EventEmitter, even though it is a C++ class, and b) we do
// not provide methods that are not present in the Browser and not documented
// on our side (e.g. hasRef).
// Save a copy of the original set of methods as a shallow clone.
const MessagePortPrototype = Object.create(
  Object.getPrototypeOf(MessagePort.prototype),
  Object.getOwnPropertyDescriptors(MessagePort.prototype));
// Set up the new inheritance chain.
Object.setPrototypeOf(MessagePort, EventEmitter);
Object.setPrototypeOf(MessagePort.prototype, EventEmitter.prototype);
// Copy methods that are inherited from HandleWrap, because
// changing the prototype of MessagePort.prototype implicitly removed them.
MessagePort.prototype.ref = MessagePortPrototype.ref;
MessagePort.prototype.unref = MessagePortPrototype.unref;

// A communication channel consisting of a handle (that wraps around an
// uv_async_t) which can receive information from other threads and emits
// .onmessage events, and a function used for sending data to a MessagePort
// in some other thread.
MessagePort.prototype[kOnMessageListener] = function onmessage(event) {
  if (event.data && event.data.type !== messageTypes.STDIO_WANTS_MORE_DATA)
    debug(`[${threadId}] received message`, event);
  // Emit the deserialized object to userland.
  this.emit('message', event.data);
};
github dcposch / webtorrent-remote / client.js View on Github external
if (!opts) opts = {}

  this._send = send

  this.clientKey = generateUniqueKey()
  this.torrents = {}

  this._destroyed = false

  var heartbeat = opts.heartbeat != null ? opts.heartbeat : 5000
  if (heartbeat > 0) {
    this._interval = setInterval(sendHeartbeat.bind(null, this), heartbeat)
  }
}

WebTorrentRemoteClient.prototype = Object.create(EventEmitter.prototype)

/**
 * Receives a message from the WebTorrentRemoteServer
 */
WebTorrentRemoteClient.prototype.receive = function (message) {
  if (message.clientKey !== this.clientKey) {
    return console.error('ignoring message, expected clientKey ' + this.clientKey +
      ': ' + JSON.stringify(message))
  }
  if (this._destroyed) {
    return console.error('ignoring message, client is destroyed: ' + this.clientKey)
  }
  switch (message.type) {
    // Public events. These are part of the WebTorrent API
    case 'infohash':
      return handleInfo(this, message)
github ostera / tldr.js / src / stores / Command.js View on Github external
import EventEmitter from 'events';
import assign from 'object-assign';
import co from 'co';
import request from 'axios';
import { decode } from 'base-64';

import Dispatcher from '../dispatchers/Main';
import { ActionTypes } from '../actions/Command';

// Internal data structure for commands
const INDEX_URL = "https://api.github.com/repos/tldr-pages/tldr/contents/pages/index.json";
let _commands = [];
let _currentCommand = {};

let CommandStore = assign( {}, EventEmitter.prototype, {

  emitChange: function () {
    this.emit("change");
  },

  addChangeListener: function(callback) {
    this.on("change", callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener("change", callback);
  },

  getCurrentCommand: function () { return _currentCommand; },

  getCommands: function () { return _commands; }
github graalvm / graaljs / lib / internal / child_process.js View on Github external
} else {
      this.emit('exit', this.exitCode, this.signalCode);
    }

    // If any of the stdio streams have not been touched,
    // then pull all the data through so that it can get the
    // eof and emit a 'close' event.
    // Do it on nextTick so that the user has one last chance
    // to consume the output, if for example they only want to
    // start reading the data once the process exits.
    process.nextTick(flushStdio, this);

    maybeClose(this);
  };
}
Object.setPrototypeOf(ChildProcess.prototype, EventEmitter.prototype);
Object.setPrototypeOf(ChildProcess, EventEmitter);


function flushStdio(subprocess) {
  const stdio = subprocess.stdio;

  if (stdio == null) return;

  for (var i = 0; i < stdio.length; i++) {
    const stream = stdio[i];
    // TODO(addaleax): This doesn't necessarily account for all the ways in
    // which data can be read from a stream, e.g. being consumed on the
    // native layer directly as a StreamBase.
    if (!stream || !stream.readable ||
        stream._readableState.readableListening ||
        stream[kIsUsedAsStdio]) {
github graalvm / graaljs / lib / domain.js View on Github external
EventEmitter.init = function() {
  Object.defineProperty(this, 'domain', {
    configurable: true,
    enumerable: false,
    value: null,
    writable: true
  });
  if (exports.active && !(this instanceof exports.Domain)) {
    this.domain = exports.active;
  }

  return eventInit.call(this);
};

const eventEmit = EventEmitter.prototype.emit;
EventEmitter.prototype.emit = function(...args) {
  const domain = this.domain;

  const type = args[0];
  const shouldEmitError = type === 'error' &&
                          this.listenerCount(type) > 0;

  // Just call original `emit` if current EE instance has `error`
  // handler, there's no active domain or this is process
  if (shouldEmitError || domain === null || domain === undefined ||
      this === process) {
    return Reflect.apply(eventEmit, this, args);
  }

  if (type === 'error') {
    const er = args.length > 1 && args[1] ?
      args[1] : new ERR_UNHANDLED_ERROR();
github KoryNunn / fastn / test / customModel.js View on Github external
if(!target){
        return;
    }

    delete target[match[1]];
    allModels.forEach(function(model){
        if(model.isAttached() && model._model === instance){
            model._events && Object.keys(model._events).forEach(function(key){
                if(model.get(key.match(/(.*?)\./)[1]) === target){
                    model.emit(key);
                }
            });
        }
    });
};
CustomModel.prototype = Object.create(EventEmitter.prototype);
CustomModel.prototype.constructor = CustomModel;
CustomModel.prototype._maxListeners = 100;
CustomModel.prototype.constructor = CustomModel;
CustomModel.prototype.attach = function(instance){
    if(this._model !== instance){
        this.detach();
    }

    allModels.add(this);
    this._attached = true;
    this._model = instance;
    this.emit('attach', instance);
};
CustomModel.prototype.detach = function(){
    allModels.delete(this);
github citelab / JAMScript / lib / jserver / ebus.js View on Github external
var EventEmitter = require('events');


function EventBus(state) {

    this.state = state;

}

EventBus.prototype = Object.create(EventEmitter.prototype);
EventBus.prototype.constructor = EventBus;

EventBus.prototype.trigger = function() {

    if (this.state.fog !== undefined)
        this.emit('fog-up', this.state.fog.id, this.state.fog.cinfo);

    if (this.state.cloud !== undefined)
        this.emit('cloud-up', this.state.cloud.id, this.state.cloud.cinfo);
}

EventBus.prototype.emitFogUp = function(id, cinfo) {

    this.state.fog = {id: id, cinfo: cinfo};
    console.log("Emiting. fog up.....................");
    this.emit('fog-up', id, cinfo);
github jupitex / sisyphe / src / dispatcher.js View on Github external
const debounce = require('lodash').debounce;
const Promise = require('bluebird');
const EventEmitter = require('events');
const Overseer = require('./overseer');

/**
 * It manage a list of Overseer. In sisyphe there is one dispatcher for one module
 * @constructor
 */
const Dispatcher = Object.create(EventEmitter.prototype);

/**
 * Init all variable of Dispatcher
 * @param {Task} task Instance of the Task file to use
 * @param {options} options
 * @param {string} options.name Type of worker
 * @return {Dispatcher}
 */
Dispatcher.init = function (task, options) {
  EventEmitter.call(this);
  this.patients = [];
  this.waitingQueue = [];
  this.tasks = task;
  this.tasks.on('failed', (job, err) => {
    this.emit('error', err);
  });
github node-apn / node-apn / lib / protocol / endpoint.js View on Github external
this.options.targetPort = this.options.port;
      this.options.host = this.options.proxy.host;
      this.options.port = this.options.proxy.port || this.options.port;
    }

    this._acquiredStreamSlots = 0;
    this._maximumStreamSlots = 0;
    this._lastSuccessPingedTime = null;
    this._pingedThreshold = (this.options.heartBeat || 60000) * 2.5;
    this._heartBeatInterval = (this.options.heartBeat || 60000);

    this._connect();
    this._heartBeatIntervalCheck = this._setupHTTP2HealthCheck();
  }

  Endpoint.prototype = Object.create(EventEmitter.prototype, {
    availableStreamSlots: {
      get: function() {
        return this._maximumStreamSlots - this._acquiredStreamSlots;
      }
    }
  });

  Endpoint.prototype._setupHTTP2Pipeline = function _setupHTTP2Pipeline() {
    const serializer = new protocol.Serializer(noopLogger.child("serializer"));
    const compressor = new protocol.Compressor(noopLogger.child("compressor"), "REQUEST");
    const deserializer = new protocol.Deserializer(noopLogger.child("deserializer"));
    const decompressor = new protocol.Decompressor(noopLogger.child("decompressor"), "RESPONSE");

    this._connection.pipe(compressor);
    compressor.pipe(serializer);
    serializer.pipe(this._socket);