https://github.com/cavejay/koala-event
Manage NodeJS Events by extending EventEmitters to support Koa-like middleware.
https://github.com/cavejay/koala-event
Last synced: 29 days ago
JSON representation
Manage NodeJS Events by extending EventEmitters to support Koa-like middleware.
- Host: GitHub
- URL: https://github.com/cavejay/koala-event
- Owner: cavejay
- License: mit
- Created: 2020-05-23T04:35:37.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2020-05-24T12:08:05.000Z (about 6 years ago)
- Last Synced: 2025-09-21T18:03:47.498Z (9 months ago)
- Language: JavaScript
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# koala-event
Manage NodeJS Events by extending EventEmitter to support Koa-like middleware.
## Install
Currently not on NPM - just hosted here.
```
npm i cavejay/koala-event
```
## Usage
The KoalaEvent Class enables the equivalent of `koa.use(fn)`.
```js
var EventEmitter = require("events").EventEmitter;
const { KoalaEvent, EventRouter } = require("../koala-event");
var emitter = new EventEmitter();
var eventHandler = new KoalaEvent();
// This function will be run on all emitted events.
eventHandler.use(async function test1(ctx, next) {
console.log("Print the event Context", ctx);
await next();
});
/**
* ctx provided to functions is:
* {
* event: ,
* data:
* }
*/
// Once the middleware/.use()s are applied then, overwrite an emitter with the an emitter that handles
// This is similar to Koa's callback()
emitter.emit = eventHandler.newEmitter(emitter);
// Proceed as normal
emitter.emit("test", "hi");
emitter.emit("something", "else");
emitter.emit("something", "else again");
```
The EventRouter Class is very similar to koa-mount's` mount('uri', fn)`. This is an effective replacement for normal events, but supports mutation of context through multiple listeners - similar to processing of a Koa request.
```js
var emitter = new EventEmitter();
const e = new EventRouter();
e.on("test", (ctx, next) => {
console.log(ctx);
});
e.on("test", () => {
console.log("I won't appear") // test's first middleware doesn't continue the flow"
})
e.on("something", (ctx, next) => {
console.log(ctx);
ctx.secret = "hi"; // Add the 'secret' after showing the initial ctx
next(); // to continue processing listeners to the 'something' event
});
e.on("something", (ctx, next) => {
console.log(ctx.secret); // the secret appended during an earlier middleware is present.
});
emitter.emit = e.newEmitter(emitter);
emitter.emit("test", "hi");
emitter.emit("something", "else");
emitter.emit("something", "again");
emitter.emit("nothing", 122); // nothing has no listener. We could make a global listener using .use (just like Koa) should we want to.
```