(function () {
function EventEmitter() {
this._listeners = {};
this.on = this.addListener;
this.once = this.addListenerOnce;
this.off = this.removeListener;
}
EventEmitter.prototype = {
constructor: EventEmitter,
addListener: function (type, fn, context) {
return this._addListener(type, fn, context, false);
},
addListenerOnce: function (type, fn, context) {
return this._addListener(type, fn, context, true);
},
removeListener: function (type, fn, context) {
if (this._hasListeners(type)) {
for (; ; ) {
var index = this._indexOfListener(type, fn, context);
if (index < 0) {
break;
}
this._listeners[type].splice(index, 1);
}
if (!this._listeners[type].length) {
delete this._listeners[type];
}
}
return this;
},
removeAllListeners: function (type) {
if (arguments.length) {
delete this._listeners[type];
} else {
this._listeners = {};
}
return this;
},
emit: function (type, args) {
args = [].slice.call(arguments, 1);
if (this._hasListeners(type)) {
var listeners = this._listeners[type];
var i = 0;
while (i < listeners.length) {
var listener = listeners[i];
listener.fn.apply(listener.context, args);
if (listener.once) {
listeners.splice(i, 1);
continue;
}
++i;
}
if (!listeners.length) {
delete this._listeners[type];
}
}
return this;
},
_addListener: function (type, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('fn must be function');
}
context = context || this;
if (!this._hasListeners(type)) {
this._listeners[type] = [];
}
var listener = {
fn,
context,
once
};
this._listeners[type].push(listener);
return this;
},
_indexOfListener: function (type, fn, context) {
context = context || this;
var listeners = this._listeners[type];
var length = listeners.length;
for (var i = 0; i < length; ++i) {
var listener = listeners[i];
if (listener.fn === fn && listener.context === context) {
return i;
}
}
return -1;
},
_hasListeners: function (type) {
return this._listeners.hasOwnProperty(type);
}
};
function hello(name) {
console.log(this);
console.log('Hello ' + name + '!');
}
function hello2(name) {
console.log('Привет, ' + name + '!');
}
function hello3(name) {
console.log('Bonjour ' + name + '!');
}
var ee = new EventEmitter;
ee.on('greeting', hello);
ee.on('greeting', hello2);
ee.once('greeting', hello3);
ee.emit('greeting', 'Foo');
ee.off('greeting', hello);
ee.emit('greeting', 'Bar');
})();
GayCoder, где все преимущества ES6?