charliewilco / cyclops

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cyclops

Build Status

Simple event emitter w. debugging that reminds me of require('events').

Rationale

There are lots of different implementations of an event emitter. The reason this exists is to extend the ability to have custom events.

import * as events from "events";

/**
 * Represents a polling timeout
 * @constructor
 */
class Poller<T> extends events.EventEmitter {
  timeout: number;

  constructor(timeout: number = 100) {
    super();
    this.timeout = timeout;
  }

  poll() {
    setTimeout(() => this.emit("poll"), this.timeout);
  }

  onPoll(cb: () => void) {
    this.on("poll", cb);
  }
}

Installation

yarn add @charliewilco/cyclops

Usage Examples

Basic

const emit = new Cyclops();
let val = 0;

emit.subscribe("mock event", (n: number) => (val = n));
emit.emit("mock event", 18);

Polling

class Poller extends Cyclops {
  constructor(timeout = 500) {
    this.timeout = timeout;
  }
  public poll() {
    setTimeout(() => this.emit("poll"), this.timeout);
  }

  public onPoll(cb) {
    this.subscribe("poll", cb);
  }
}

let count = 0;
const poll = new Poller(1000);

poll.onPoll(() => {
  count++;

  console.log(count);

  poll.poll();
});

poll.poll();

About


Languages

Language:TypeScript 100.0%