1.1.0 • Published 5 years ago

@charliewilco/cyclops v1.1.0

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

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({}, { debug: true });
let val = 0;

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

Polling

const emit = new Cyclops();

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

  onPoll(cb) {
    emit.subscribe("poll", cb);
  }
}
let count = 0;
const poll = new Poller(1000);

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

  console.log(count);

  poll.poll();
});

poll.poll();