-
Notifications
You must be signed in to change notification settings - Fork 9
/
listeners.js
56 lines (50 loc) · 1.69 KB
/
listeners.js
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
55
56
const hook = require('./hook');
const {removeEventListener, addEventListener, slice, Map, Object} = require('./natives');
const handlers = new Map();
function fire(that, listener, args) {
if (listener) {
if (listener.handleEvent) {
return listener.handleEvent.apply(listener, args);
}
else {
return listener.apply(that, args);
}
}
}
function getAddEventListener(win, event) {
return function(type, handler, options) {
let listener = handler;
if (type === event) {
if (!handlers.has(handler)) {
handlers.set(handler, function () {
hook(this);
const args = slice(arguments);
fire(this, handler, args);
});
}
listener = handlers.get(handler);
}
return addEventListener(this || win, type, listener, options);
}
}
function getRemoveEventListener(win, event) {
return function(type, handler, options) {
let listener = handler;
if (type === event) {
listener = handlers.get(handler);
handlers.delete(handler);
}
return removeEventListener(this || win, type, listener, options);
}
}
function hookEventListenersSetters(win, event) {
Object.defineProperty(win.EventTarget.prototype, 'addEventListener', {
configurable: true, writable: true,
value: getAddEventListener(win, event),
});
Object.defineProperty(win.EventTarget.prototype, 'removeEventListener', {
configurable: true, writable: true,
value: getRemoveEventListener(win, event),
});
}
module.exports = hookEventListenersSetters;