events#EventEmitter JavaScript Examples

The following examples show how to use events#EventEmitter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: rpc.js    From desktop with GNU General Public License v3.0 6 votes vote down vote up
constructor() {
    this.emitter = new EventEmitter();
    this.ipc = ipcRenderer;
    if (window.__rpcId) {
      setTimeout(() => {
        this.id = window.__rpcId;
        this.ipc.on(this.id, this.ipcListener);
        this.emitter.emit("ready", null);
      }, 0);
    } else {
      this.ipc.on("init", (ev, uid) => {
        // we cache so that if the object
        // gets re-instantiated we don't
        // wait for a `init` event
        window.__rpcId = uid;
        this.id = uid;
        this.ipc.on(uid, this.ipcListener);
        this.emitter.emit("ready", null);
      });
    }
  }
Example #2
Source File: context.js    From aresrpg with MIT License 6 votes vote down vote up
initial_world = {
  ...floor1,
  /** @type {NodeJS.EventEmitter} */
  events: new EventEmitter(),
  next_entity_id: 1,
  next_window_id: 1, // 0 is the player inventory
  /** @type {() => Object} Remove type to remove circular references */
  get: () => world,
  screens: {},
}
Example #3
Source File: panel.js    From remix-live-beta with MIT License 6 votes vote down vote up
constructor (profile) {
    super(profile)
    this.events = new EventEmitter()
    this.contents = {}
    this.active = undefined

    // View where the plugin HTMLElement leaves
    this.view = yo`<div id="plugins" class="${css.plugins}"></div>`
  }
Example #4
Source File: theme-module.js    From remix-live-beta with MIT License 6 votes vote down vote up
constructor (registry) {
    super(profile)
    this.events = new EventEmitter()
    this._deps = {
      config: registry.get('config').api
    }
    this.themes = themes.reduce((acc, theme) => ({ ...acc, [theme.name]: theme }), {})
    this.active = this._deps.config.get('settings/theme') ? this._deps.config.get('settings/theme') : 'Dark'
  }
Example #5
Source File: jsep_protocol_driver.js    From android-emulator-webrtc with Apache License 2.0 6 votes vote down vote up
/**
   * Creates an instance of JsepProtocol.
   * @param {EmulatorService} emulator Service used to make the gRPC calls
   * @param {RtcService} rtc Service used to open up the rtc calls.
   * @param {boolean} poll True if we should use polling
   * @param {callback} onConnect optional callback that is invoked when a stream is available
   * @param {callback} onDisconnect optional callback that is invoked when the stream is closed.
   * @memberof JsepProtocol
   */
  constructor(emulator, rtc, poll, onConnect, onDisconnect) {
    this.emulator = emulator;
    this.rtc = rtc;
    this.events = new EventEmitter();

    // Workaround for older emulators that send messages out of order
    // and do not handle all answers properly.
    this.old_emu_patch = {
      candidates: [],
      sdp: null,
      haveOffer: false,
      answer: false,
    };

    this.poll = poll;
    this.guid = null;
    this.stream = null;
    this.event_forwarders = {};
    if (onConnect) this.events.on("connected", onConnect);
    if (onDisconnect) this.events.on("disconnected", onDisconnect);
  }
Example #6
Source File: logcat.js    From android-emulator-webrtc with Apache License 2.0 6 votes vote down vote up
/**
   * Creates a logcat stream.
   *
   *  The authentication service should implement the following methods:
   * - `authHeader()` which must return a set of headers that should be send along with a request.
   * - `unauthorized()` a function that gets called when a 401 was received.
   *
   * @constructor
   * @param {object} uriOrEmulator
   * @param {object} auth
   */
  constructor(uriOrEmulator, auth) {
    if (uriOrEmulator instanceof EmulatorControllerService) {
      this.emulator = uriOrEmulator;
    } else {
      this.emulator = new EmulatorControllerService(uriOrEmulator, auth);
    }
    this.offset = 0;
    this.lastline = "";
    this.stream = null;
    this.events = new EventEmitter();
    this.refreshRate = 1000;
    this.timerID = null;
  }
Example #7
Source File: Batch.js    From action-install-gh-release with Apache License 2.0 6 votes vote down vote up
/**
     * Creates an instance of Batch.
     * @param concurrency -
     */
    constructor(concurrency = 5) {
        /**
         * Number of active operations under execution.
         */
        this.actives = 0;
        /**
         * Number of completed operations under execution.
         */
        this.completed = 0;
        /**
         * Offset of next operation to be executed.
         */
        this.offset = 0;
        /**
         * Operation array to be executed.
         */
        this.operations = [];
        /**
         * States of Batch. When an error happens, state will turn into error.
         * Batch will stop execute left operations.
         */
        this.state = BatchStates.Good;
        if (concurrency < 1) {
            throw new RangeError("concurrency must be larger than 0");
        }
        this.concurrency = concurrency;
        this.emitter = new EventEmitter();
    }
Example #8
Source File: index.js    From vulncost with MIT License 5 votes vote down vote up
// this is weird…

export function getImports(fileName, text, language) {
  const emitter = new EventEmitter();
  setTimeout(async () => {
    try {
      emitter.emit('package', finder(fileName).next().filename);
    } catch (e) {
      // noop
    }
    try {
      const imports = getPackages(fileName, text, language).filter(info => {
        if (nativePackages.includes(info.name.toLowerCase())) {
          return false;
        }

        if (info.name.startsWith('.')) {
          return false;
        }

        if (info.name.startsWith('~')) {
          return false;
        }

        if (info.name.trim() == '') {
          return false;
        }

        if (info.name.includes('/') && !info.name.startsWith('@')) {
          // mutating…
          info.name = info.name.split('/').shift();
        }

        const valid = validate(info.name);

        if (valid.errors) {
          // invalid package name, so isn't real, so we'll bail
          return false;
        }

        return true;
      });
      emitter.emit('start', imports);
      const promises = imports
        .map(packageInfo => getPackageInfo(packageInfo))
        .map(promise =>
          promise.then(packageInfo => {
            emitter.emit('calculated', packageInfo);
            return packageInfo;
          })
        );
      const packages = await Promise.all(promises);
      emitter.emit('done', packages);
    } catch (e) {
      console.log(e);
      emitter.emit('error', e);
    }
  }, 0);
  return emitter;
}
Example #9
Source File: wallet-seed.js    From spl-token-wallet with Apache License 2.0 5 votes vote down vote up
walletSeedChanged = new EventEmitter()
Example #10
Source File: updater.js    From loa-details with GNU General Public License v3.0 5 votes vote down vote up
updaterEventEmitter = new EventEmitter()
Example #11
Source File: http-bridge.js    From loa-details with GNU General Public License v3.0 5 votes vote down vote up
httpServerEventEmitter = new EventEmitter()
Example #12
Source File: BufferScheduler.js    From action-install-gh-release with Apache License 2.0 5 votes vote down vote up
/**
     * Creates an instance of BufferScheduler.
     *
     * @param readable - A Node.js Readable stream
     * @param bufferSize - Buffer size of every maintained buffer
     * @param maxBuffers - How many buffers can be allocated
     * @param outgoingHandler - An async function scheduled to be
     *                                          triggered when a buffer fully filled
     *                                          with stream data
     * @param concurrency - Concurrency of executing outgoingHandlers (>0)
     * @param encoding - [Optional] Encoding of Readable stream when it's a string stream
     */
    constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) {
        /**
         * An internal event emitter.
         */
        this.emitter = new EventEmitter();
        /**
         * An internal offset marker to track data offset in bytes of next outgoingHandler.
         */
        this.offset = 0;
        /**
         * An internal marker to track whether stream is end.
         */
        this.isStreamEnd = false;
        /**
         * An internal marker to track whether stream or outgoingHandler returns error.
         */
        this.isError = false;
        /**
         * How many handlers are executing.
         */
        this.executingOutgoingHandlers = 0;
        /**
         * How many buffers have been allocated.
         */
        this.numBuffers = 0;
        /**
         * Because this class doesn't know how much data every time stream pops, which
         * is defined by highWaterMarker of the stream. So BufferScheduler will cache
         * data received from the stream, when data in unresolvedDataArray exceeds the
         * blockSize defined, it will try to concat a blockSize of buffer, fill into available
         * buffers from incoming and push to outgoing array.
         */
        this.unresolvedDataArray = [];
        /**
         * How much data consisted in unresolvedDataArray.
         */
        this.unresolvedLength = 0;
        /**
         * The array includes all the available buffers can be used to fill data from stream.
         */
        this.incoming = [];
        /**
         * The array (queue) includes all the buffers filled from stream data.
         */
        this.outgoing = [];
        if (bufferSize <= 0) {
            throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`);
        }
        if (maxBuffers <= 0) {
            throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`);
        }
        if (concurrency <= 0) {
            throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`);
        }
        this.bufferSize = bufferSize;
        this.maxBuffers = maxBuffers;
        this.readable = readable;
        this.outgoingHandler = outgoingHandler;
        this.concurrency = concurrency;
        this.encoding = encoding;
    }
Example #13
Source File: simple_png_view.test.js    From android-emulator-webrtc with Apache License 2.0 5 votes vote down vote up
stream = new EventEmitter()
Example #14
Source File: emulator_web_client.js    From android-emulator-webrtc with Apache License 2.0 5 votes vote down vote up
constructor(options, auth) {
    super(options);
    this.auth = auth;
    this.events = new EventEmitter();
    this.events.on("error", e => {console.log("low level gRPC error: " + JSON.stringify(e));})
  }
Example #15
Source File: remixAppManager.js    From remix-live-beta with MIT License 5 votes vote down vote up
constructor (plugins) {
    super()
    this.event = new EventEmitter()
    this.pluginsDirectory = 'https://raw.githubusercontent.com/ethereum/remix-plugins-directory/master/build/metadata.json'
    this.pluginLoader = new PluginLoader()
    this.permissionHandler = new PermissionHandler()
  }
Example #16
Source File: analysis-tab.js    From remix-live-beta with MIT License 5 votes vote down vote up
constructor (registry) {
    super(profile)
    this.event = new EventManager()
    this.events = new EventEmitter()
    this.registry = registry
  }
Example #17
Source File: mobs.js    From aresrpg with MIT License 5 votes vote down vote up
/** @param {import('./context.js').InitialWorld} world */
export function register(world) {
  const mobs = world.mob_positions.map(({ position, type, level }, i) => {
    const { speed = DEFAULT_SPEED, health } = Entities[type]
    const initial_state = {
      path: [position],
      open: [],
      closed: [],
      start_time: 0,
      speed:
        (1 / (speed * MOVEMENT_SPEED_TO_BLOCKS_PER_SECOND)) *
        1000 /* ms/block */,
      health /* halfheart */,
      blackboard: {},
      attack_sequence_number: 0,
      wakeup_at: 0,
      sleep_id: null,
      look_at: { player: false, yaw: 0, pitch: 0 },
    }

    const actions = new PassThrough({ objectMode: true })
    const events = new EventEmitter()
    events.setMaxListeners(Infinity)

    const entity_id = world.next_entity_id + i

    aiter(actions).reduce(async (last_state, action) => {
      const state = await reduce_mob(last_state, action, {
        world: world.get(),
        type,
        entity_id,
      })
      events.emit(Mob.STATE, state)
      return state
    }, initial_state)

    setImmediate(() => events.emit(Mob.STATE, initial_state))

    const get_state = last_event_value(events, Mob.STATE)

    return {
      entity_id,
      type,
      level,
      events,
      get_state,
      constants: entitiesByName[Entities[type].minecraft_entity],
      position(time = Date.now()) {
        const { path, start_time, speed } = get_state()

        return path_position({ path, time, start_time, speed })
      },
      dispatch(action_type, payload, time = Date.now()) {
        actions.write({ type: action_type, payload, time })
      },
    }
  })

  observe_mobs(mobs)

  const { next_entity_id } = world

  return {
    ...world,
    next_entity_id: next_entity_id + mobs.length,
    mobs: {
      all: mobs,
      by_entity_id(id) {
        if (id >= next_entity_id && id <= next_entity_id + mobs.length)
          return mobs[id - next_entity_id]
        else return null
      },
    },
  }
}
Example #18
Source File: pusher.js    From aresrpg with MIT License 5 votes vote down vote up
emitter = new EventEmitter()
Example #19
Source File: index.js    From swap-frontend with GNU General Public License v3.0 4 votes vote down vote up
function getLibrary(provider_) {
  let provider = provider_
  if (!provider || !provider.trx) {
    provider = window.tronWeb || createTronWeb()
  }
  const tronWeb = provider
  const getBlockNumber = async () => {
    const block = await tronWeb.trx.getCurrentBlock()
    return block.block_header.raw_data.number
  }
  const emitter = new EventEmitter()
  const on = (...args) => {
    emitter.on(...args)
  }
  const removeListener = (...args) => {
    emitter.removeListener(...args)
  }
  const lookupAddress = async (...args) => {
    console.warn('library.lookupAddress() not implemented', args)
  }
  const getBalance = async address => {
    try {
      const balance = await tronWeb.trx.getBalance(toTronAddr(address))
      //console.log('getBalance', address, balance.toString())
      // console.log(`${address} balance is`, balance)
      return balance
    } catch (err) {
      console.error('error getting balance from tronweb', { address })
      throw err
    }
  }

  /*
   *  retry versioni
  const getTransactionReceipt = async hash => {
    const res = await promiseRetry(async retry => {
      console.log({ hash, tronWeb })
      const info = await tronWeb.trx.getTransactionInfo(hash)
      if (!info.id) {
        retry()
      }
      return info
    })
    console.log(res)
    return res
  }
  */

  const getTransactionReceipt = async hash => {
    const info = await tronWeb.trx.getTransactionInfo(hash)
    if (!info.id) {
      return null
    }
    return info
  }

  const toTronAddr = str => {
    return tronWeb.address.fromHex(`41${str.slice(2)}`)
  }

  // poll for new blocks
  let lastBlockNumber
  setInterval(async () => {
    // query new block
    const block = await promiseRetry(async retry => {
      try {
        const b = await tronWeb.trx.getCurrentBlock()
        if (!b || !b.block_header || !b.block_header.raw_data) {
          return retry()
        }
        return b
      } catch (err) {
        console.error({ tronWeb, err })
        return retry()
      }
    })
    const blockNumber = block.block_header.raw_data.number
    if (lastBlockNumber !== blockNumber) {
      // console.log(`new block ${blockNumber}`, block)
      lastBlockNumber = blockNumber
      emitter.emit('block', block)
    }
  }, 1000)

  return {
    provider,
    getBlockNumber,
    getBalance,
    on,
    lookupAddress,
    removeListener,
    getTransactionReceipt,
    toTronAddr
  }
}
Example #20
Source File: context.js    From aresrpg with MIT License 4 votes vote down vote up
/**
 * The following code handle the pipeline, it works as following
 *
 * state = initial_state
 * on packets + on actions
 *   |> transform_action
 *   |> (state = reduce_state(state))
 *
 * @param {import('minecraft-protocol').Client} client
 */
export async function create_context(client) {
  log.info(
    {
      username: client.username,
      uuid: client.uuid,
      id: client.id,
    },
    'Client connected'
  )

  const controller = new AbortController()
  const actions = new PassThrough({ objectMode: true })

  client.once('end', () => {
    log.info(
      { username: client.username, uuid: client.uuid },
      'Client disconnected'
    )

    actions.end()
    controller.abort()
  })

  client.on('error', error => log.error(error, 'Client error'))

  const packets = aiter(
    abortable(on(client, 'packet', { signal: controller.signal }))
  ).map(([payload, { name }]) => ({
    type: `packet/${name}`,
    payload,
  }))

  const save_state = state => {
    log.info(
      { username: client.username, uuid: client.uuid },
      'Saving to database'
    )
    Database.push({
      key: client.uuid.toLowerCase(),
      value: saved_state(state),
    })
  }

  /** @type {NodeJS.EventEmitter} */
  const events = new EventEmitter()
  const player_state = await Database.pull(client.uuid.toLowerCase())

  aiter(combineAsyncIterators(actions[Symbol.asyncIterator](), packets))
    .map(transform_action)
    .reduce(
      (last_state, action) => {
        const state = reduce_state(last_state, action)
        events.emit(Context.STATE, state)
        return state
      },
      // default nickname is the client username, and is overriden by the loaded player state
      {
        ...initial_state,
        nickname: client.username,
        ...player_state,
        last_connection_time: Date.now(),
      }
    )
    .then(state => ({
      ...state,
      last_disconnection_time: Date.now(),
    }))
    .then(save_state)
    .catch(error => {
      // TODO: what to do here if we can't save the client ?
      log.error(error, 'State error')
    })

  const get_state = last_event_value(events, Context.STATE)

  return {
    client,
    world,
    events,
    signal: controller.signal,
    get_state,
    inside_view: inside_view(get_state),
    dispatch(type, payload) {
      actions.write({ type, payload })
    },
  }
}