观察者模式的事件管理器可以让游戏中各模块间的功能调用以事件响应的方式相对独立开来,使得各模块间的功能相对更加独立。TS中的实现方法与JS类似,只是某些语法略有不同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
*
* @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) {
// 通过guid识别function
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);
}
}
}
}
}