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 "use strict"; |
| 19 |
| 20 /** |
| 21 * Registers and emits named events. |
| 22 * |
| 23 * @constructor |
| 24 */ |
| 25 exports.EventEmitter = function() |
| 26 { |
| 27 this._listeners = Object.create(null); |
| 28 }; |
| 29 |
| 30 exports.EventEmitter.prototype = { |
| 31 /** |
| 32 * Adds a listener for the specified event name. |
| 33 * |
| 34 * @param {string} name |
| 35 * @param {function} listener |
| 36 */ |
| 37 on: function(name, listener) |
| 38 { |
| 39 if (name in this._listeners) |
| 40 this._listeners[name].push(listener); |
| 41 else |
| 42 this._listeners[name] = [listener]; |
| 43 }, |
| 44 |
| 45 /** |
| 46 * Removes a listener for the specified event name. |
| 47 * |
| 48 * @param {string} name |
| 49 * @param {function} listener |
| 50 */ |
| 51 off: function(name, listener) |
| 52 { |
| 53 let listeners = this._listeners[name]; |
| 54 if (listeners) |
| 55 { |
| 56 let idx = listeners.indexOf(listener); |
| 57 if (idx != -1) |
| 58 listeners.splice(idx, 1); |
| 59 } |
| 60 }, |
| 61 |
| 62 /** |
| 63 * Adds a one time listener and returns a promise that |
| 64 * is resolved the next time the specified event is emitted. |
| 65 * |
| 66 * @return {Promise} |
| 67 */ |
| 68 once: function(name) |
| 69 { |
| 70 return new Promise(resolve => |
| 71 { |
| 72 let listener = () => |
| 73 { |
| 74 this.off(name, listener); |
| 75 resolve(); |
| 76 }; |
| 77 |
| 78 this.on(name, listener); |
| 79 }); |
| 80 }, |
| 81 |
| 82 /** |
| 83 * Calls all previously added listeners for the given event name. |
| 84 * |
| 85 * @param {string} name |
| 86 * @param {...*} [arg] |
| 87 */ |
| 88 emit: function(name) |
| 89 { |
| 90 let listeners = this._listeners[name]; |
| 91 if (listeners) |
| 92 { |
| 93 let args = []; |
| 94 for (let i = 1; i < arguments.length; i++) |
| 95 args.push(arguments[i]); |
| 96 |
| 97 let currentListeners = listeners.slice(); |
| 98 for (let listener of currentListeners) |
| 99 listener.apply(null, args); |
| 100 } |
| 101 } |
| 102 }; |
OLD | NEW |