1.1.0 • Published 6 years ago

ep.js v1.1.0

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

ep.js

ep - EventProxy, a tiny tools based on Sub/Pub pattern for async programming.

npm install ep.js -S

usage

var EP = require('ep.js');

var ep = new EP;

ep.on('update', function(content) {
  console.log(content);
});

setTimeout(function() {
  ep.emit('update', ['abc']);
}, 1000);

// log 'abc' 1000ms later

API

EP.prototype.on

Subscribe an event:

var EP = require('./ep'),
    ep = new EP;


ep.on('update', function(content) {
  console.log(content);
});

setTimeout(function() {
  ep.emit('update', ['abc']);
}, 1000);

// log 'abc' 1000ms later

EP.prototype.any

Callback will be called after any event has been emitted.

ep.any(['A', 'B'], function() {
  console.log('A ||B ');
});

setTimeout(function() {
  ep.emit('A');
}, 1000);

EP.prototype.once

Only call the callback once, after the event has been emitted, the callback will be removed.

ep.once('A', function() {
  console.log('AAAA');
});

ep.emit('A');
ep.emit('A');

// log 'AAAA' once

EP.prototype.remove

Remove certain callback or all the callbacks of certain event.

function callback_1(){/* ignored */};
function callback_2(){/* ignored */};
ep.once('A', callback_1);
ep.once('A', callback_2);

// remove all the callback of event 'A'
ep.remove('A');

// nothing happend
ep.emit('A'); 


ep.once('A', callback_1);
ep.once('A', callback_2);

// only remove callback_1
ep.remove('A', callback_1);

EP.prototype.emit

Emit an event.

This method takes 3 arguments:

  • 1th: event name
  • 2th: an array of arguments passed to callback,
  • 3th: the context of callback
EP.prototype.emit = function(string event, array arguments, any context){}

// if argument is an array `A = [...]`, must put it into an array :
var A = [...];
ep.emit('event', [A]);

EP.ep

A static EP instance.

var ep = require('ep.js').ep;

ep.on('A', callback);
ep.emit('A');
// ...

License

MIT