@funjs/emitter
v1.3.0
Published
Simple and fast functional event emitter...
Downloads
12
Readme
What is it?
A simple fast and functional route parser, for Javascript in Node and the browser. Its api is inspired by EventEmitter2, but is implemented in a more functional way, don't rely in 'this' keyword.
How do I install it?
yarn add @funjs/emitter
or
npm install --save @funjs/emitter
How do I use it?
const Emitter = require('@funjs/emitter');
const emitter = Emitter();
emitter.on('users/:action=(insert|update)/:id', ({ action, id }, data) => {
console.log(`action: ${action}`);
console.log(`id: ${id}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users/insert/1', { id: 1, name: 'Joe', age: 33 });
// action: insert
// id: 1
// data: {"id":1,"name":"Joe","age":33}
Splat operator return the section position as key, starting by 1:
const Emitter = require('@funjs/emitter');
const emitter = Emitter();
emitter.on('*/*/:id', (e, data) => {
console.log(`event: ${JSON.stringify(e)}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users/insert/1', { id: 1, name: 'Joe', age: 33 });
// event: {"0":"users","1":"insert","id":"1"}
// data: {"id":1,"name":"Joe","age":33}
Also works with custom delimiter and named section symbols?
const Emitter = require('@funjs/emitter');
const emitter = Emitter({ delimiter: '.', namedSection: '$' });
emitter.on('users.$action=(insert|update).id', ({ action, id }, data) => {
console.log(`action: ${action}`);
console.log(`id: ${id}`);
console.log(`data: ${JSON.stringify(data)}`);
});
emitter.emit('users.insert.1', { id: 1, name: 'Joe', age: 33 });
// action: insert
// id: 1
// data: {"id":1,"name":"Joe","age":33}
What can I use in my events routes?
| Example | Description |
| --------------- | -------- |
| :name
| a named parameter to capture from the route up to /
, ?
, or end of string |
| *
| a splat to capture from the route up to ?
or end of string |
| :name=(a|b|c) | a named parameter group that doesn't have to be part of the query. Can contain nested optional groups, params, and splats
| anything else | free form literals |
Some examples:
/some/:thing
/users/:id/comments/:comment/rating/:rating
/*/foo/*
/books/:section=(Romance|Horror)/:title
TODO:
- [x] Basic API
- [x] Customizables delimeters and named segment symbols
- [ ] Reverse Matching
- [ ] Implement all features of EventEmitter2
- [ ] Emplement a "RethinkDBish" query API