OLD | NEW |
| (Empty) |
1 /* | |
2 * This file is part of Adblock Plus <https://adblockplus.org/>, | |
3 * Copyright (C) 2006-2016 Eyeo GmbH | |
4 * | |
5 * Adblock Plus is free software: you can redistribute it and/or modify | |
6 * it under the terms of the GNU General Public License version 3 as | |
7 * published by the Free Software Foundation. | |
8 * | |
9 * Adblock Plus is distributed in the hope that it will be useful, | |
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 * GNU General Public License for more details. | |
13 * | |
14 * You should have received a copy of the GNU General Public License | |
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. | |
16 */ | |
17 | |
18 /** @module events */ | |
19 | |
20 "use strict"; | |
21 | |
22 /** | |
23 * Registers and emits names events. | |
24 * | |
25 * @constructor | |
26 */ | |
27 exports.EventEmitter = function() | |
28 { | |
29 this._listeners = Object.create(null); | |
30 }; | |
31 | |
32 exports.EventEmitter.prototype = { | |
33 /** | |
34 * Adds a listener for the specified event name. | |
35 * | |
36 * @param {string} name | |
37 * @param {function} listener | |
38 */ | |
39 on: function(name, listener) | |
40 { | |
41 if (name in this._listeners) | |
42 this._listeners[name].push(listener); | |
43 else | |
44 this._listeners[name] = [listener]; | |
45 }, | |
46 | |
47 /** | |
48 * Removes a listener for the specified event name. | |
49 * | |
50 * @param {string} name | |
51 * @param {function} listener | |
52 */ | |
53 off: function(name, listener) | |
54 { | |
55 let listeners = this._listeners[name]; | |
56 if (listeners) | |
57 { | |
58 let idx = listeners.indexOf(listener); | |
59 if (idx != -1) | |
60 listeners.splice(idx, 1); | |
61 } | |
62 }, | |
63 | |
64 /** | |
65 * Calls all previously added listeners for the given event name. | |
66 * | |
67 * @param {string} name | |
68 * @param {...*} [arg] | |
69 */ | |
70 emit: function(name) | |
71 { | |
72 let listeners = this._listeners[name]; | |
73 if (listeners) | |
74 { | |
75 let args = []; | |
76 for (let i = 1; i < arguments.length; i++) | |
77 args.push(arguments[i]); | |
78 | |
79 let currentListeners = listeners.slice(); | |
80 for (let listener of currentListeners) | |
81 listener.apply(null, args); | |
82 } | |
83 } | |
84 }; | |
OLD | NEW |