4
Really, really lightweight event emitting for Node and the browser.
6
(though Node already has [event emitting built in][1] so I don't know why you'd
7
use this there. This is directly inspired by Node's and doesn't even have all of
8
the functionality that Node's event emitter has.)
10
This library has three goals:
12
1. Make it easy and intuitive to listen for and initiate events on an object.
13
2. Be as small as possible. Right now the minified version comes in at 407 bytes
15
3. Not pollute the global namespace or the objects it modifies with a bunch of
16
crap. I define crap as anything that is not the API.
18
There are many other [wonderful libraries that do similar things][2], but none
19
of them worked exactly how I wanted them to work or met all the goals above.
24
In the browser, just download `smokesignals.js` or `smokesignals.unminified.js`
25
and put your choice in a place you can access from your webpage.
29
npm install smokesignals
34
In the browser include the Smoke Signals script:
36
<script src="smokesignals.js"></script>
40
var smokesignals = require('smokesignals');
45
Make any object an event emitter:
48
smokesignals.convert(jill);
50
Or if you prefer constructors:
53
smokesignals.convert(this);
55
var jill = new Person();
57
Now you can listen for events:
59
function listener(name) {
60
window.alert('Hello ' + name + '!');
62
jill.on('say hello', listener);
66
jill.emit('say hello', 'Jack');
67
// alerts: "Hello Jack!"
69
And remove a listener:
71
jill.off('say hello', listener);
73
Or if you only want to listen for an event once:
75
jill.once('another event', function() {
76
window.alert("I'll only be called once!");
78
jill.emit('another event');
80
Or remove all listeners for an event:
82
jill.off('say hello');
84
Or if you want to remove ALL listeners:
86
// just reconvert the object...
87
smokesignals.convert(jill);
89
That's it! One global object (`smokesignals`) and when used it adds 4 methods to
90
your objects (`on`, `once`, `off` and `emit`).
92
By the way, all methods are chainable:
94
var jill = smokesignals.convert({})
95
.on('event one', function() { ... })
96
.on('event two', function() { ... })
98
.once('event three', function() { ... })
102
[1]: http://nodejs.org/docs/latest/api/events.html
103
[2]: http://microjs.com/#events