*
* @shihua
* 2016.08.29
*/
class EventManager {
private static _listeners = {};
private static guid: number = 1;
public static sub(type: string,fn): void {
if (typeof this._listeners[type] === 'undefined') {
this._listeners[type] = [];
}
if (typeof fn === 'function') {
this._listeners[type].push(fn);
fn.guid = this.guid;
this.guid++;
}
}
public static unsub(type: string, fn): void {
var arrayEvent = this._listeners[type];
if (typeof type === 'string' && arrayEvent instanceof Array) {
if (typeof fn === 'function') {
for (var i = 0,length = arrayEvent.length; i < length; i += 1) {
if (arrayEvent[i].guid === fn.guid) {
this._listeners[type].splice(i,1);
break;
}
}
} else {
delete this._listeners[type];
}
}
}
public static pub(type: string, ...data: any[]): void {
var arrayEvent = this._listeners[type];
var handlerArgs = Array.prototype.slice.call(arguments, 1);
if (arrayEvent instanceof Array) {
for (var i = 0,length = arrayEvent.length; i < length; i += 1) {
if (typeof arrayEvent[i] === 'function') {
arrayEvent[i].apply(this, handlerArgs);
}
}
}
}
}