Skip to content

Commit 781acee

Browse files
committed
Removing of events
1 parent 66d14fc commit 781acee

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

‎chapters/events.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,22 @@ Bark twice a second:
4848
setInterval(function(){
4949
simon.emit('bark');
5050
}, 500);
51+
52+
## Removing Event Listeners
53+
54+
As we have seen event listeners are simply functions which are called when we `emit()` an event. Although not seen often we can remove these listeners by calling the `removeListener(type, callback)` method. In the example below we emit the _message_ "foo bar" every `300` milliseconds, which has the callback of `console.log()`. After 1000 milliseconds we call `removeListener()` with the same arguments that we passed to `on()` originally. To compliment this method is `removeAllListeners(type)` which removes all listeners associated to the given _type_.
55+
56+
var EventEmitter = require('events').EventEmitter;
57+
58+
var emitter = new EventEmitter;
59+
60+
emitter.on('message', console.log);
61+
62+
setInterval(function(){
63+
emitter.emit('message', 'foo bar');
64+
}, 300);
65+
66+
setTimeout(function(){
67+
emitter.removeListener('message', console.log);
68+
}, 1000);
69+

‎src/events/removing.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
/**
3+
* Module dependencies.
4+
*/
5+
6+
var EventEmitter = require('events').EventEmitter;
7+
8+
var emitter = new EventEmitter;
9+
10+
emitter.on('message', console.log);
11+
12+
setInterval(function(){
13+
emitter.emit('message', 'foo bar');
14+
}, 300);
15+
16+
setTimeout(function(){
17+
emitter.removeListener('message', console.log);
18+
}, 1000);

0 commit comments

Comments
 (0)