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
const Events = function (params) {
this.clientList = [];
};

Events.prototype.$emit = function () {
const eventname = Array.prototype.slice.call(arguments, 0, 1)[0];
if (this.clientList[eventname].length) {
this.clientList[eventname].forEach((listener) => {
// listener(Array.prototype.slice.call(arguments, 1));
listener(Array.prototype.slice.apply(arguments, [1]));
});
}
};
Events.prototype._getClientList = function () {
return this.clientList;
};
// 订阅者
Events.prototype.$on = function (eventName, callback) {
// 判断clientList是否存在派发的事件数组
if (!this.clientList[eventName]) {
// 创建下标为eventName的数组,保存每个eventName订阅者对应的监听事件
this.clientList[eventName] = [];
}
// 如果已经存在eventName监听数组
// 将新的监听事件加入
this.clientList[eventName] = [...this.clientList[eventName], callback];
};

const events = new Events();
// 监听事件 - 订阅者
const zhangsan = function () {
events.$on("baweixinkong-5.28", function (data) {
console.log("zhangli", data);
});
};
const lisi = function () {
events.$on("baweixinkong-5.28", function (data) {
console.log("lisi", data);
});
events.$on("baweixinkong-5.27", function (data) {
console.log("lisi" + data);
});
};
zhangsan();
lisi();
events.$on("baweixinkong-5.28", function (data) {
console.log("mazi", data);
});
events.$on("baweixinkong-5.21", function (data) {
console.log(data);
});
// 派发事件 - 发布者
events.$emit("baweixinkong-5.28", "5.28新闻,你好么么哒");
// Events.$emit("baweixinkong-5.27", "你好么么哒");