customEvent
# 目录
在很多的框架中,关于提供到框架外部的钩子的处理方法简单的有以下几种:
- 直接在代码中注入回调、让框架类继承自 emitter 通过 emitter 处理消息 (OOP)
- 在框架中导出 emitter 通过 emitter 处理消息
- 使用原生的 EventTarget API 处理消息。
- (以及在 webpack 源码中会介绍另外一种钩子机制,此处不再赘述。)
在 single-spa 中使用了 EventTarget API 来处理钩子消息,以便开发者能够在应用的生命周期的关键时刻注入钩子的业务逻辑,使框架本身更加灵活可扩展。
在本节的内容中,将详细介绍 EventTarget API。
# EventTarget
The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.
# 谁继承了 EventTarget?
Element
, and its children, as well as Document
and Window
, are the most common event targets, but other objects can be event targets, too. For example XMLHttpRequest
, AudioNode
, and AudioContext
are also event targets.
# Methods
- EventTarget.addEventListener(): Registers an event handler of a specific event type on the EventTarget.
- EventTarget.removeEventListener():Removes an event listener from the EventTarget.
- EventTarget.dispatchEvent():Dispatches an event to this EventTarget.
参考:
# CustomEvent
使用如下方法兼容 CustomEvent
- modern browser:global.CustomEvent
- ie9+:document.createEvent、document.initCustomEvent
- ie8-:document.createEventObject
// https://github.com/webmodules/custom-event/blob/master/index.js
// global 适用于 nodejs
var NativeCustomEvent = global.CustomEvent;
// 是否使用原生 CustomEvent
function useNative () {
try {
var p = new NativeCustomEvent('cat', { detail: { foo: 'bar' } });
return 'cat' === p.type && 'bar' === p.detail.foo;
} catch (e) {
}
return false;
}
/**
* Cross-browser `CustomEvent` constructor.
*
* https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent.CustomEvent
*
* @public
*/
module.exports = useNative() ? NativeCustomEvent :
// IE >= 9
'undefined' !== typeof document && 'function' === typeof document.createEvent ? function CustomEvent (type, params) {
// 支持 ie9 以上,在 document 上创建事件并且初始化
// ie9+ 支持 createEvent 和 initCustomEvent
var e = document.createEvent('CustomEvent');
if (params) {
e.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else {
e.initCustomEvent(type, false, false, void 0);
}
return e;
} :
// IE <= 8
function CustomEvent (type, params) {
// ie 8- 支持 createEventObject
var e = document.createEventObject();
e.type = type;
if (params) {
e.bubbles = Boolean(params.bubbles);
e.cancelable = Boolean(params.cancelable);
e.detail = params.detail;
} else {
e.bubbles = false;
e.cancelable = false;
e.detail = void 0;
}
return e;
}
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
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
参考:
编辑 (opens new window)
上次更新: 2022/09/06, 14:25:16