Book
Search…
Simple eventEmitter

实现目标

1
Event.on("test", function(result) {
2
console.log(result);
3
})
4
Event.on("test", function(result) {
5
console.log("test");
6
})
7
Event.emit("test", "hello world");
Copied!
  1. 1.
    监听事件
  2. 2.
    发出事件
  3. 3.
    事件队列

思路

实现一个对象,监听方法on将事件加入到队列中,触发方法emit将找到对应的队列中的事件,并触发回调。

对象实现

1
let Event = {}; //
2
3
Object.defineProperty(Event, "_cbQueue", {
4
value: {},
5
writable: true,
6
enumerable: false, //将枚举设置为false,防止在copy属性的时候,不会被复制。
7
configurable: true
8
});
9
10
Event.on = function (type, handler) {
11
this._cbQueue = this._cbQueue || {};
12
this._cbQueue[type] = this._cbQueue[type] || [];
13
this._cbQueue[type].push(handler);
14
return this;
15
}
16
17
Event.emit = function (type, data) {
18
if (this._cbQueue[type]) {
19
this._cbQueue[type].forEach(cb => {
20
cb(data);
21
});
22
}else {
23
throw new Error('not found custom event : ' + type)
24
}
25
}
26
27
Event.off = function (type, handle) {
28
var handles = this._cbQueue[type];
29
if (handles) {
30
if (!handle) {
31
this._cbQueue[type] = [];
32
} else {
33
for (var i = 0; i < handles.length; i++) {
34
if (handles[i] === handle) {
35
this._cbQueue[type].splice(i, 1);
36
}
37
}
38
}
39
}
40
41
}
42
module.exports = Event;
Copied!

ES6 Class 实现

1
class Event {
2
constructor() {
3
this._cbQueue = {};
4
}
5
on(type, handler) {
6
if (!this._cbQueue[type]) {
7
this._cbQueue[type] = [handler]
8
}else{
9
this._cbQueue[type].push(handler)
10
}
11
12
}
13
emit(type, data) {
14
if (this._cbQueue[type]) {
15
this._cbQueue[type].forEach(cb => {
16
cb(data)
17
});
18
} else {
19
throw new Error('not found custom event : ' + type)
20
}
21
}
22
off(type, handler) {
23
const handles = this._cbQueue[type];
24
if (handles) {
25
if (!handler) {
26
this._cbQueue[type] = [];
27
} else {
28
for (var i = 0; i < handles.length; i++) {
29
if (handles[i] === handler) {
30
this._cbQueue[type].splice(i, 1);
31
}
32
}
33
}
34
}
35
}
36
}
37
38
module.exports = Event
Copied!
Last modified 2yr ago