events#EventEmitter TypeScript 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: ipcInterface.ts    From AIPerf with MIT License 6 votes vote down vote up
/**
     * Construct a IPC proxy
     * @param proc the process to wrap
     * @param acceptCommandTypes set of accepted commands for this process
     */
    constructor(proc: ChildProcess, acceptCommandTypes: Set<string>) {
        this.acceptCommandTypes = acceptCommandTypes;
        this.outgoingStream = <Writable>proc.stdio[ipcOutgoingFd];
        this.incomingStream = <Readable>proc.stdio[ipcIncomingFd];
        this.eventEmitter = new EventEmitter();
        this.readBuffer = Buffer.alloc(0);

        this.incomingStream.on('data', (data: Buffer) => { this.receive(data); });
        this.incomingStream.on('error', (error: Error) => { this.eventEmitter.emit('error', error); });
        this.outgoingStream.on('error', (error: Error) => { this.eventEmitter.emit('error', error); });
    }
Example #2
Source File: SignalingClient.spec.ts    From amazon-kinesis-video-streams-webrtc-sdk-js-with-amazon-cognito with MIT No Attribution 6 votes vote down vote up
class MockWebSocket extends EventEmitter {
    static instance: MockWebSocket;

    public readyState: number;
    public send = jest.fn();
    public close = jest.fn().mockImplementation(() => {
        if (this.readyState === RealWebSocket.CONNECTING || this.readyState === RealWebSocket.OPEN) {
            this.readyState = RealWebSocket.CLOSING;
            setTimeout(() => {
                if (this.readyState === RealWebSocket.CLOSING) {
                    this.readyState = RealWebSocket.CLOSED;
                    this.emit('close');
                }
            }, 5);
        }
    });

    public constructor() {
        super();
        this.readyState = RealWebSocket.CONNECTING;
        setTimeout(() => {
            if (this.readyState === RealWebSocket.CONNECTING) {
                this.readyState = RealWebSocket.OPEN;
                this.emit('open');
            }
        }, 10);
        MockWebSocket.instance = this;
    }

    public addEventListener(...args: any[]): void {
        super.addListener.apply(this, args);
    }

    public removeEventListener(...args: any[]): void {
        super.removeListener.apply(this, args);
    }
}
Example #3
Source File: DrawerStore.tsx    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
export class DrawerStore extends EventEmitter {
  private drawers: Map<string, boolean> = new Map()

  open(id: string) {
    this.drawers.set(id, true)
    this.emit(id, true)
  }

  close(id: string) {
    this.drawers.set(id, false)
    this.emit(id, false)
  }
}
Example #4
Source File: TSServer.ts    From typescript-strict-plugin with MIT License 6 votes vote down vote up
constructor() {
    this._responseEventEmitter = new EventEmitter();
    this._responseCommandEmitter = new EventEmitter();
    const tsserverPath = require.resolve('typescript/lib/tsserver');

    const server = fork(tsserverPath, {
      stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
      // env: { TSS_LOG: '-logToFile true -file ./ts.log -level verbose' }, // creates tsserver log from tests
    });
    this._exitPromise = new Promise((resolve, reject) => {
      server.on('exit', (code: string) => resolve(code));
      server.on('error', (reason: string) => reject(reason));
    });
    server.stdout?.setEncoding('utf-8');
    server.stdout?.on('data', (data: string) => {
      const [, , res] = data.split('\n');
      const obj = JSON.parse(res) as ServerResponse;
      if (obj.type === 'event') {
        this._responseEventEmitter.emit(obj.event, obj);
      } else if (obj.type === 'response') {
        this._responseCommandEmitter.emit(obj.command, obj);
      }
      this.responses.push(obj);
    });
    this._isClosed = false;
    this._server = server;
    this._seq = 0;
    this.responses = [];
  }
Example #5
Source File: socket.ts    From voxelsrv with MIT License 6 votes vote down vote up
constructor(toClient: EventEmitter, toServer: EventEmitter, server?: string) {
		super();
		this.server = server;
		this.toClient = toClient;
		this.toServer = toServer;

		this.toClient.on('open', () => {
			setTimeout(() => this.toClient.emit('connection', {}), 500);
		});

		this.toClient.on('error', (e: string) => {
			if (this.closed) return;
			this.closed = true;
			setTimeout(() => this.toClient.emit('PlayerKick', { reason: e }), 500);
		});

		this.toClient.on('close', () => {
			if (this.closed) return;
			this.closed = true;
			setTimeout(() => this.toClient.emit('PlayerKick', { reason: `Connection closed!` }), 500);
		});
	}
Example #6
Source File: eip1193.ts    From useDApp with MIT License 6 votes vote down vote up
export function subscribeToProviderEvents(
  provider: EventEmitter | undefined,
  onUpdate: (updatedNetwork: Partial<Network>) => void,
  onDisconnect: (error: Error) => void
) {
  if (provider?.on) {
    const onConnectListener = (info: { chainId: string } | undefined): void => {
      if (info?.chainId) {
        onUpdate({ chainId: Number(info.chainId) })
      }
    }
    provider.on('connect', onConnectListener)

    const onDisconnectListener = (error: any): void => {
      onDisconnect(new Error(error))
    }
    provider.on('disconnect', onDisconnectListener)

    const onChainChangedListener = (chainId: string): void => {
      onUpdate({ chainId: Number(chainId) })
    }
    provider.on('chainChanged', onChainChangedListener)

    const onAccountsChangedListener = (accounts: string[]): void => {
      onUpdate({ accounts })
    }
    provider.on('accountsChanged', onAccountsChangedListener)

    return () => {
      provider.removeListener('connect', onConnectListener)
      provider.removeListener('disconnect', onDisconnectListener)
      provider.removeListener('chainChanged', onChainChangedListener)
      provider.removeListener('accountsChanged', onAccountsChangedListener)
    }
  }

  return () => undefined
}
Example #7
Source File: Bot.ts    From tf2autobot with MIT License 6 votes vote down vote up
private addAsyncListener(
        emitter: EventEmitter,
        event: string,
        listener: (...args) => Promise<void>,
        checkCanEmit: boolean
    ): void {
        emitter.on(event, (...args): void => {
            if (!checkCanEmit || this.canSendEvents()) {
                // eslint-disable-next-line @typescript-eslint/no-misused-promises
                setImmediate(listener, ...args);
            }
        });
    }
Example #8
Source File: transitioner.ts    From phaneron with GNU General Public License v3.0 6 votes vote down vote up
constructor(
		clContext: nodenCLContext,
		layerID: string,
		consumerFormat: VideoFormat,
		clJobs: ClJobs,
		endEvent: EventEmitter,
		layerUpdate: (ts: number[]) => void
	) {
		this.clContext = clContext
		this.layerID = `${layerID} transition`
		this.consumerFormat = consumerFormat
		this.clJobs = clJobs
		this.endEvent = endEvent
		this.silence = new Silence(this.consumerFormat)
		this.black = new Black(this.clContext, this.consumerFormat, this.layerID)
		this.layerUpdate = layerUpdate
		this.audType = 'cut'
		this.vidType = 'cut'
		this.numFrames = 0
		this.curFrame = 0
		this.nextType = 'cut'
		this.nextNumFrames = 0
	}
Example #9
Source File: PoeWindow.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
class PoeWindowClass extends EventEmitter {
  private _isActive: boolean = false

  get bounds () { return OW.bounds }

  get isActive () { return this._isActive }

  set isActive (active: boolean) {
    if (this.isActive !== active) {
      if (active) {
        logger.verbose('Is active', { source: 'poe-window' })
      } else {
        logger.verbose('Not focused', { source: 'poe-window' })
      }
      this._isActive = active
      this.emit('active-change', this._isActive)
    }
  }

  get uiSidebarWidth () {
    // sidebar is 370px at 800x600
    const ratio = 370 / 600
    return Math.round(this.bounds.height * ratio)
  }

  attach (window: BrowserWindow) {
    OW.events.on('focus', () => { this.isActive = true })
    OW.events.on('blur', () => { this.isActive = false })

    OW.attachTo(window, config.get('windowTitle'))
  }

  onAttach (cb: (hasAccess: boolean | undefined) => void) {
    OW.events.on('attach', (e: AttachEvent) => {
      cb(e.hasAccess)
    })
  }
}
Example #10
Source File: pluginTypes.ts    From DittoPlusPlus with MIT License 6 votes vote down vote up
export class ProcessAbstract extends EventEmitter {
  send: (
    type: string,
    msgData?: any,
    cb?: (error: any, response: any) => void,
  ) => void;
  initialize: (args: ProcessInitArgs) => void;
  onAppFocus?(e: any): void;
  onAppUnFocus?(e: any): void;
  onIconClick?(e: any): void;
}
Example #11
Source File: parser.ts    From ts-edifact with Apache License 2.0 6 votes vote down vote up
constructor(configuration?: Configuration) {
        super();

        EventEmitter.apply(this);

        if (configuration) {
            this.configuration = configuration;
        } else {
            this.configuration = new Configuration();
        }
        this.validator = this.configuration.validator;
        this.tokenizer = new Tokenizer(this.configuration);
        this.state = States.EMPTY;
    }
Example #12
Source File: Functions.ts    From Mandroc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * A helper function for determining if a value is an event emitter.
 * @param input
 * @since 2.0.0
 */
export function isEmitter(input: unknown): input is EventEmitter {
  return (
    input !== "undefined" &&
    input !== void 0 &&
    typeof (input as EventEmitter).on === "function" &&
    typeof (input as EventEmitter).emit === "function"
  );
}
Example #13
Source File: router.ts    From Daemon with GNU Affero General Public License v3.0 6 votes vote down vote up
// Routing controller class (singleton class)
class RouterApp extends EventEmitter {
  public readonly middlewares: Array<Function>;

  constructor() {
    super();
    this.middlewares = [];
  }

  emitRouter(event: string, ctx: RouterContext, data: any) {
    try {
      // service logic routing trigger point
      super.emit(event, ctx, data);
    } catch (error) {
      responseError(ctx, error);
    }
    return this;
  }

  on(event: string, fn: (ctx: RouterContext, data: any) => void) {
    // logger.info(` Register event: ${event} `);
    return super.on(event, fn);
  }

  use(fn: (event: string, ctx: RouterContext, data: any, next: Function) => void) {
    this.middlewares.push(fn);
  }

  getMiddlewares() {
    return this.middlewares;
  }
}
Example #14
Source File: flv-preprocessor.ts    From las with MIT License 6 votes vote down vote up
/**
     * 构造函数
     * @param eventEmitter 事件派发器
     * @param onFlvKeyframe 关键帧位置回调
     */
    constructor(eventEmitter: EventEmitter, onFlvKeyframe: FlvKeyframeCallback<T>) {
        this._eventEmitter = eventEmitter;
        this._onFlvKeyframe = onFlvKeyframe;
        this._cache = new Cache();
        this._parseLen = FlvSize.FLV_HEAD_LEN;
        this._parseFunc = this._parseFlvHead;
        this._result = { list: [] };
    }
Example #15
Source File: index.ts    From metamask-snap-polkadot with Apache License 2.0 6 votes vote down vote up
// returns or creates new emitter based on provided origin
  public getEventEmitter(origin: string): StrictEventEmitter<EventEmitter, T> {
    if (!this.emitters) {
      this.emitters = {
        [origin]: new EventEmitter()
      };
    } else if (!this.emitters[origin]) {
      this.emitters[origin] = new EventEmitter();
    }
    return this.emitters[origin];
  }
Example #16
Source File: JitsiTrack.d.ts    From binaural-meet with GNU General Public License v3.0 6 votes vote down vote up
declare class JitsiTrack extends EventEmitter {
  constructor(
    conference: Object,
    stream: MediaStream,
    track: MediaStreamTrack,
    streamInactiveHandler: Function,
    trackMediaType: TMediaType,
    videoType: string,
  );
  videoType?: string
  disposed: boolean
  getType: () => 'video' | 'audio'
  isAudioTrack: () => boolean
  isWebRTCTrackMuted: () => boolean
  isVideoTrack: () => boolean
  isLocal: () => boolean
  isLocalAudioTrack: () => boolean
  getOriginalStream: () => MediaStream
  getStreamId: () => string | null
  getTrack: () => MediaStreamTrack
  getTrackLabel: () => string
  getTrackId: () => string | null
  getUsageLabel: () => string
  attach: (container: HTMLElement) => void
  detach: (container: HTMLElement) => void
  dispose: () => Promise<void>
  getId: () => string | null
  isActive: () => boolean
  setAudioLevel: (audioLevel: number, tpc: TraceablePeerConnection) => void
  getMSID: () => string | null
  setAudioOutput: (audioOutputDeviceId: string) => Promise<void>
}
Example #17
Source File: index.ts    From toogoodtogo-bot with MIT License 6 votes vote down vote up
async init() {
    this.eventEmitter = await new EventEmitter();

    this.dataManager = new DataManager({ eventEmitter: this.eventEmitter });

    if (Config.notifications.telegram.enabled)
      this.telegram = new Telegram({ eventEmitter: this.eventEmitter });

    if (Config.notifications.console.enabled)
      this.console = new Console({ eventEmitter: this.eventEmitter });

    if (Config.notifications.desktop.enabled)
      this.desktop = new Desktop({ eventEmitter: this.eventEmitter });
  }
Example #18
Source File: remoteMachineTrainingService.ts    From AIPerf with MIT License 6 votes vote down vote up
constructor(@component.Inject timer: ObservableTimer) {
        this.remoteOS = 'linux';
        this.metricsEmitter = new EventEmitter();
        this.trialJobsMap = new Map<string, RemoteMachineTrialJobDetail>();
        this.trialSSHClientMap = new Map<string, Client>();
        this.machineSSHClientMap = new Map<RemoteMachineMeta, SSHClientManager>();
        this.jobQueue = [];
        this.expRootDir = getExperimentRootDir();
        this.remoteExpRootDir = this.getRemoteExperimentRootDir();
        this.timer = timer;
        this.log = getLogger();
        this.trialSequenceId = -1;
        this.logCollection = 'none';
        this.log.info('Construct remote machine training service.');
    }
Example #19
Source File: go.ts    From atom-ide-golang with MIT License 6 votes vote down vote up
export class Go extends EventEmitter {
    env: any;
    public constructor() {
        super();

        let goEnv = this.spawn(['env'], {async: false}) as cp.SpawnSyncReturns<string>
        if (goEnv.error) {
            atom.notifications.addError(`${pkg.name} unable to get the go env are you sure go is installed?`, {
                dismissable: true,
                description: goEnv.error.message,
                detail: goEnv.error.stack,
            })
            return
        }
        this.env = util.parseEnv(goEnv.stdout.toString())
    }

    public tool(name: string, args: string[], options?: any, callback?: any): cp.ChildProcess {
        options = options === null || options === undefined ? {} : options
        options = Object.assign({
            env: process.env,
        }, options)

        let toolpath = path.join(this.env.GOPATH, 'bin', name)
        return cp.execFile(toolpath, args, options, callback)
    }

    public spawn(args: string[], options: any) {
        options = options === null || options === undefined ? {} : options
        if ('async' in options) {
            if (options.async) {
                return cp.spawn('go', args, options)
            } else {
                return cp.spawnSync('go', args, options)
            }
        }
        return cp.spawn('go', args, options)
    }
}
Example #20
Source File: paiTrainingService.ts    From AIPerf with MIT License 6 votes vote down vote up
constructor() {
        this.log = getLogger();
        this.metricsEmitter = new EventEmitter();
        this.trialJobsMap = new Map<string, PAITrialJobDetail>();
        this.jobQueue = [];
        this.expRootDir = path.join('/nni', 'experiments', getExperimentId());
        this.experimentId = getExperimentId();
        this.paiJobCollector = new PAIJobInfoCollector(this.trialJobsMap);
        this.paiTokenUpdateInterval = 7200000; //2hours
        this.logCollection = 'none';
        this.log.info('Construct paiBase training service.');
    }
Example #21
Source File: index.ts    From walletconnect-v2-monorepo with Apache License 2.0 5 votes vote down vote up
public events: any = new EventEmitter();
Example #22
Source File: l10n.ts    From WebCord with MIT License 5 votes vote down vote up
langDialog = new EventEmitter()
Example #23
Source File: index.ts    From toogoodtogo-bot with MIT License 5 votes vote down vote up
eventEmitter: EventEmitter
Example #24
Source File: clJobQueue.ts    From phaneron with GNU General Public License v3.0 5 votes vote down vote up
private readonly runEvents: EventEmitter
Example #25
Source File: index.ts    From toogoodtogo-bot with MIT License 5 votes vote down vote up
eventEmitter: EventEmitter;
Example #26
Source File: heads.ts    From phaneron with GNU General Public License v3.0 5 votes vote down vote up
private readonly eventDone: EventEmitter
Example #27
Source File: index.ts    From toogoodtogo-bot with MIT License 5 votes vote down vote up
eventEmitter: EventEmitter;
Example #28
Source File: layer.ts    From phaneron with GNU General Public License v3.0 5 votes vote down vote up
private readonly endEvent: EventEmitter
Example #29
Source File: index.ts    From toogoodtogo-bot with MIT License 5 votes vote down vote up
eventEmitter: EventEmitter | null;