• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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'use strict';
23require('../common');
24const assert = require('assert');
25const events = require('events');
26
27let callbacks_called = [];
28
29const e = new events.EventEmitter();
30
31function callback1() {
32  callbacks_called.push('callback1');
33  e.on('foo', callback2);
34  e.on('foo', callback3);
35  e.removeListener('foo', callback1);
36}
37
38function callback2() {
39  callbacks_called.push('callback2');
40  e.removeListener('foo', callback2);
41}
42
43function callback3() {
44  callbacks_called.push('callback3');
45  e.removeListener('foo', callback3);
46}
47
48e.on('foo', callback1);
49assert.strictEqual(e.listeners('foo').length, 1);
50
51e.emit('foo');
52assert.strictEqual(e.listeners('foo').length, 2);
53assert.deepStrictEqual(['callback1'], callbacks_called);
54
55e.emit('foo');
56assert.strictEqual(e.listeners('foo').length, 0);
57assert.deepStrictEqual(['callback1', 'callback2', 'callback3'],
58                       callbacks_called);
59
60e.emit('foo');
61assert.strictEqual(e.listeners('foo').length, 0);
62assert.deepStrictEqual(['callback1', 'callback2', 'callback3'],
63                       callbacks_called);
64
65e.on('foo', callback1);
66e.on('foo', callback2);
67assert.strictEqual(e.listeners('foo').length, 2);
68e.removeAllListeners('foo');
69assert.strictEqual(e.listeners('foo').length, 0);
70
71// Verify that removing callbacks while in emit allows emits to propagate to
72// all listeners
73callbacks_called = [];
74
75e.on('foo', callback2);
76e.on('foo', callback3);
77assert.strictEqual(e.listeners('foo').length, 2);
78e.emit('foo');
79assert.deepStrictEqual(['callback2', 'callback3'], callbacks_called);
80assert.strictEqual(e.listeners('foo').length, 0);
81