JavaScript观察者模式(发布订阅模式)

实现示例

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
50
51
52
53
54
var eventuality = function (that) {
var registry = {};
//触发事件
that.fire = function (event) {
var array,
func,
handler,
i,
type = typeof event === "string" ? event : event.type;
if (registry.hasOwnProperty(type)) {
array = registry[type];
for (i = 0; i < array.length; i += 1) {
handler = array[i];
func = handler.method;
if (typeof func === "string") {
func = this[func];
}
func.apply(this, handler.parameters || [event]);
}
}
return this;
};
that.on = function (type, method, parameters) {
var handler = {
method: method,
parameters: parameters,
};
if (registry.hasOwnProperty(type)) {
registry[type].push(handler);
} else {
registry[type] = [handler];
}
return this;
};
return that;
};
var objectEventTest = {
a: 1,
b: 2,
getA: function () {
console.log(this.a);
},
getB: function () {
console.log(this.b);
},
showC: function (c) {
console.log(c);
},
};
eventuality(objectEventTest);
objectEventTest.on("show", "getA");
objectEventTest.on("show", "getB");
objectEventTest.on("show1", "showC", ["show C!!"]);
objectEventTest.fire("show");