0.4.1 • Published 4 years ago

event-type v0.4.1

Weekly downloads
1
License
ISC
Repository
github
Last release
4 years ago

event-type

A general purpose, promise based event system.

Build Status

Usage

Attach some event emitter using EventType.prototype.dispatch():

import { EventType } from "event-type";
import http from "http";

const httpRequests = new EventType();

http.createServer((request, response) => {
  httpRequests.dispatch([request, response]);
}).listen(8000);

Listen for a single event using EventType.prototype.listen():

httpRequests.listen().then(([request, response]) => {
  console.log(`${request.method} ${request.url}`);
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello, World!\n");
});

Keep listening for events:

/* --async context-- */
while (true) {
  const [request, response] = await httpRequests.listen();
  console.log(`${request.method} ${request.url}`);
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello, World!\n");
}

Or, most preferably, leverage EventType.prototype[Symbol.asyncIterator]():

/* --async context-- */
for await (const [request, response] of httpRequests) {
  console.log(`${request.method} ${request.url}`);
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello, World!\n");
}

Examples

Multiplex two sources of events:

import { EventType } from "event-type";
import http from "http";

const httpRequests = new EventType();

http.createServer(function (request, response) {
  httpRequests.dispatch([request, response]);
}).listen(8000);

http.createServer(function (request, response) {
  httpRequests.dispatch([request, response]);
}).listen(9000);

/* --async context-- */
for await (const [request, response] of httpRequests) {
  console.log(`${request.method} ${request.url}`);
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello, World!\n");
}
0.4.1

4 years ago

0.3.0

4 years ago

0.4.0

4 years ago

0.2.0

5 years ago

0.1.0

5 years ago