modify-in-emit.js
 1  // Copyright Joyent, Inc. and other Node contributors.
 2  //
 3  // Permission is hereby granted, free of charge, to any person obtaining a
 4  // copy of this software and associated documentation files (the
 5  // "Software"), to deal in the Software without restriction, including
 6  // without limitation the rights to use, copy, modify, merge, publish,
 7  // distribute, sublicense, and/or sell copies of the Software, and to permit
 8  // persons to whom the Software is furnished to do so, subject to the
 9  // following conditions:
10  //
11  // The above copyright notice and this permission notice shall be included
12  // in all copies or substantial portions of the Software.
13  //
14  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17  // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18  // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19  // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20  // USE OR OTHER DEALINGS IN THE SOFTWARE.
21  
22  var assert = require('assert');
23  var events = require('../');
24  
25  var callbacks_called = [];
26  
27  var e = new events.EventEmitter();
28  
29  function callback1() {
30    callbacks_called.push('callback1');
31    e.on('foo', callback2);
32    e.on('foo', callback3);
33    e.removeListener('foo', callback1);
34  }
35  
36  function callback2() {
37    callbacks_called.push('callback2');
38    e.removeListener('foo', callback2);
39  }
40  
41  function callback3() {
42    callbacks_called.push('callback3');
43    e.removeListener('foo', callback3);
44  }
45  
46  e.on('foo', callback1);
47  assert.equal(1, e.listeners('foo').length);
48  
49  e.emit('foo');
50  assert.equal(2, e.listeners('foo').length);
51  assert.deepEqual(['callback1'], callbacks_called);
52  
53  e.emit('foo');
54  assert.equal(0, e.listeners('foo').length);
55  assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
56  
57  e.emit('foo');
58  assert.equal(0, e.listeners('foo').length);
59  assert.deepEqual(['callback1', 'callback2', 'callback3'], callbacks_called);
60  
61  e.on('foo', callback1);
62  e.on('foo', callback2);
63  assert.equal(2, e.listeners('foo').length);
64  e.removeAllListeners('foo');
65  assert.equal(0, e.listeners('foo').length);
66  
67  // Verify that removing callbacks while in emit allows emits to propagate to
68  // all listeners
69  callbacks_called = [];
70  
71  e.on('foo', callback2);
72  e.on('foo', callback3);
73  assert.equal(2, e.listeners('foo').length);
74  e.emit('foo');
75  assert.deepEqual(['callback2', 'callback3'], callbacks_called);
76  assert.equal(0, e.listeners('foo').length);