-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathobject.js
118 lines (106 loc) · 2.62 KB
/
object.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* Created by hustcc on 18/6/9.
* Contract: [email protected]
*/
import debounce from '../debounce';
import { SensorClassName, SensorTabIndex, SizeSensorId } from '../constant';
export const createSensor = (element, whenDestroy) => {
let sensor = undefined;
// callback
let listeners = [];
/**
* create object DOM of sensor
* @returns {HTMLObjectElement}
*/
const newSensor = () => {
// adjust style
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative'
}
const obj = document.createElement('object');
obj.onload = () => {
obj.contentDocument.defaultView.addEventListener('resize', resizeListener);
// 直接触发一次 resize
resizeListener();
};
obj.style.display = 'block'
obj.style.position = 'absolute'
obj.style.top = '0'
obj.style.left = '0'
obj.style.height = '100%'
obj.style.width = '100%'
obj.style.overflow = 'hidden'
obj.style.pointerEvents = 'none'
obj.style.zIndex = '-1'
obj.style.opacity = '0'
obj.setAttribute('class', SensorClassName);
obj.setAttribute('tabindex', SensorTabIndex);
obj.type = 'text/html';
// append into dom
element.appendChild(obj);
// for ie, should set data attribute delay, or will be white screen
obj.data = 'about:blank';
return obj;
};
/**
* trigger listeners
*/
const resizeListener = debounce(() => {
// trigger all listener
listeners.forEach(listener => {
listener(element);
})
});
/**
* listen with one callback function
* @param cb
*/
const bind = cb => {
// if not exist sensor, then create one
if (!sensor) {
sensor = newSensor();
}
if (listeners.indexOf(cb) === -1) {
listeners.push(cb);
}
};
/**
* destroy all
*/
const destroy = () => {
if (sensor && sensor.parentNode) {
if (sensor.contentDocument) {
// remote event
sensor.contentDocument.defaultView.removeEventListener('resize', resizeListener);
}
// remove dom
sensor.parentNode.removeChild(sensor);
// initial variable
element.removeAttribute(SizeSensorId);
sensor = undefined;
listeners = [];
whenDestroy && whenDestroy();
}
};
/**
* cancel listener 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,
};
};