Skip to content

Commit

Permalink
Initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrykuzmenkov committed Nov 20, 2015
1 parent 8edd228 commit e8c0969
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 1 deletion.
51 changes: 50 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,51 @@
# edispatcher
Event Dispatcher
======
Tiny dependency free event dispatcher


## Install

Use npm to install just run

```bash
npm install edispatcher
```

## Usage

```javascript
var dispatcher = require('edispatcher');

dispatcher.on('event', function (event, data) {
console.log('Got event with data ' + data);
});

dispatcher.send('event', 'data');
```

## Methods

### on(event_name, callback)

Dispatch triggered event
- *event_name* - name of event as string
- *callback* - callback function to trigger. It applies event name, passed data, source and event suscribers optional

The method returns id of subscriber

### off(id)

Disable trigger handler
- *id* - identifier of subscriber

### all(callback)

Execute on any triggered event
- *callback* - callback function to trigger

### send(event_name, data, source)

Trigger new event
- *event_name* - name of event to be triggered as string
- *data* - data that should be passed
- *source* - trigger source
33 changes: 33 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module.exports = {
subscribers: {},

on: function(event_name, callback) {
(this.subscribers[event_name] = this.subscribers[event_name] || []).push(
callback
);
return callback;
},

off: function(id) {
for (var event_name in this.subscribers) {
var event_subscribers = this.subscribers[event_name];
for (var i = 0; i < event_subscribers.length; i++) {
if (event_subscribers[i] === id) {
event_subscribers.splice(i, 1);
}
}
}
},

all: function(callback) {
return this.on("*", callback);
},

send: function(event_name, data, source) {
var event_subscribers =
(this.subscribers[event_name] || []).concat(this.subscribers["*"] || []);
for (var i = 0; i < event_subscribers.length; i++) {
event_subscribers[i](event_name, data, source, event_subscribers);
}
}
};
19 changes: 19 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "edispatcher",
"version": "1.0.0",
"description": "Tiny dependency free event dispatcher",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/dmitrykuzmenkov/edispatcher.git"
},
"author": "Dmitry Kuzmenkov <[email protected]>",
"license": "MIT",
"bugs": {
"url": "https://github.com/dmitrykuzmenkov/edispatcher/issues"
},
"homepage": "https://github.com/dmitrykuzmenkov/edispatcher#readme"
}

0 comments on commit e8c0969

Please sign in to comment.