event-emitter

说明

模拟实现 EventEmitter

源码

用法

eventEmitter.test.ts
1
import { EventEmitter } from "../../utility/algorithm/event-emitter";
2
3
// ? EventEmitter
4
describe('EventEmitter tests', () => {
5
test("EventEmitter.handleOn should put handlers into events and return the handler's own index", () => {
6
const event = new EventEmitter({});
7
const fun1 = function () {
8
console.log('fun1');
9
}
10
const fun2 = function () {
11
console.log('fun2');
12
}
13
const received = [
14
{
15
type: 'click',
16
handler: fun1,
17
},
18
{
19
type: 'click',
20
handler: fun2,
21
}
22
];
23
const expected = [
24
{
25
type: 'click',
26
index: 0,
27
},
28
{
29
type: 'click',
30
index: 1,
31
}
32
];
33
34
received.forEach(function (v, i) {
35
const result = event.handleOn(v.type, v.handler);
36
expect(result).toEqual(expected[i]);
37
});
38
});
39
40
test('EventEmitter.handleRemove should remove the `dest handler` from events', () => {
41
const event = new EventEmitter({});
42
const fun1 = function () {
43
console.log('fun1');
44
}
45
const fun2 = function () {
46
console.log('fun2');
47
}
48
49
const r1 = event.handleOn('click', fun1);
50
const r2 = event.handleOn('click', fun2);
51
52
event.handleRemove(r2);
53
54
let result: boolean = false;
55
const events = event.events;
56
events['click'].forEach(function (v, i) {
57
if (i === r2.index) {
58
if (!v) {
59
result = true;
60
}
61
}
62
});
63
64
expect(result).toBeTruthy();
65
});
66
});
Copied!

API

Name
Type
Description
handleOn
(type: string, handler: EventHandler) => {
type: string, index: number
}
放置事件
handleEmit
(type: string) => EventEmitter
发射事件
handleRemove
(options: { type: string, index: number, },) => EventEmitter
移除某 type 的某个handler
最近更新 1yr ago
复制链接