-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathresizeObserver.js
87 lines (75 loc) · 1.44 KB
/
resizeObserver.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Created by hustcc on 18/7/5.
* Contract: [email protected]
*/
import { SizeSensorId } from '../constant';
import debounce from '../debounce';
export const createSensor = (element, whenDestroy) => {
let sensor = undefined;
// callback
let listeners = [];
/**
* trigger listeners
*/
const resizeListener = debounce(() => {
// trigger all
listeners.forEach(listener => {
listener(element);
})
});
/**
* create ResizeObserver sensor
* @returns
*/
const newSensor = () => {
const s = new ResizeObserver(resizeListener);
// listen element
s.observe(element);
// trigger once
resizeListener();
return s;
};
/**
* listen with callback
* @param cb
*/
const bind = cb => {
if (!sensor) {
sensor = newSensor();
}
if (listeners.indexOf(cb) === -1) {
listeners.push(cb);
}
};
/**
* destroy
*/
const destroy = () => {
sensor.disconnect();
listeners = [];
sensor = undefined;
element.removeAttribute(SizeSensorId);
whenDestroy && whenDestroy();
};
/**
* cancel bind
* @param cb
*/
const unbind = cb => {
const idx = listeners.indexOf(cb);
if (idx !== -1) {
listeners.splice(idx, 1);
}
// no listener, and sensor is exist
// then destroy the sensor
if (listeners.length === 0 && sensor) {
destroy();
}
};
return {
element,
bind,
destroy,
unbind,
};
};