1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 var util = require('util');
20 function EventEmitter() {
24 module.exports.EventEmitter = EventEmitter;
27 EventEmitter.prototype.emit = function(type) {
32 // About to emit 'error' event but there are no listeners for it.
33 if (type === 'error' && !this._events.error) {
34 var err = arguments[1];
35 if (err instanceof Error) {
38 throw Error("Uncaught 'error' event");
43 var listeners = this._events[type];
44 if (util.isArray(listeners)) {
45 listeners = listeners.slice();
46 var len = arguments.length;
47 var args = new Array(len - 1);
48 for (var i = 1; i < len; ++i) {
49 args[i - 1] = arguments[i];
51 for (var i = 0; i < listeners.length; ++i) {
52 listeners[i].apply(this, args);
61 EventEmitter.prototype.addListener = function(type, listener) {
62 if (!util.isFunction(listener)) {
63 throw new TypeError('listener must be a function');
69 if (!this._events[type]) {
70 this._events[type] = [];
73 this._events[type].push(listener);
79 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
82 EventEmitter.prototype.once = function(type, listener) {
83 if (!util.isFunction(listener)) {
84 throw new TypeError('listener must be a function');
88 // here `this` is this not global, because EventEmitter binds event object
89 // for this when it calls back the handler.
90 this.removeListener(f.type, f);
91 f.listener.apply(this, arguments);
95 f.listener = listener;
103 EventEmitter.prototype.removeListener = function(type, listener) {
104 if (!util.isFunction(listener)) {
105 throw new TypeError('listener must be a function');
108 var list = this._events[type];
109 if (Array.isArray(list)) {
110 for (var i = list.length - 1; i >= 0; --i) {
111 if (list[i] == listener ||
112 (list[i].listener && list[i].listener == listener)) {
124 EventEmitter.prototype.removeAllListeners = function(type) {
125 if (arguments.length === 0) {
128 delete this._events[type];