Skip to content
/ emitter Public

A simple and fast functional event emitter for Node and the Browser

License

Notifications You must be signed in to change notification settings

fun-js/emitter

Repository files navigation

travis build Dependency Status devDependency Status Codecov MIT License semantic-release

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:

  • Basic API
  • Customizables delimeters and named segment symbols
  • Reverse Matching
  • Implement all features of EventEmitter2
  • Emplement a "RethinkDBish" query API

About

A simple and fast functional event emitter for Node and the Browser

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published