UNPKG

2.35 kBJavaScriptView Raw
1import '../../utils/index.js';
2import { CallbackManager, MethodHandler } from '../../utils/handler.js';
3import { throttle } from '../../utils/lodash.js';
4
5const callbackManager = new CallbackManager();
6let deviceMotionListener;
7const INTERVAL_MAP = {
8 game: {
9 interval: 20,
10 frequency: 50
11 },
12 ui: {
13 interval: 60,
14 frequency: 16.67
15 },
16 normal: {
17 interval: 200,
18 frequency: 5
19 }
20};
21/**
22 * 停止监听设备方向的变化。
23 */
24const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
25 const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete });
26 try {
27 window.removeEventListener('deviceorientation', deviceMotionListener, true);
28 return handle.success();
29 }
30 catch (e) {
31 return handle.fail({ errMsg: e.message });
32 }
33};
34/**
35 * 开始监听设备方向的变化。
36 */
37const startDeviceMotionListening = ({ interval = 'normal', success, fail, complete } = {}) => {
38 const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete });
39 try {
40 const intervalObj = INTERVAL_MAP[interval];
41 if (window.DeviceOrientationEvent) {
42 if (deviceMotionListener) {
43 stopDeviceMotionListening();
44 }
45 deviceMotionListener = throttle((evt) => {
46 callbackManager.trigger({
47 alpha: evt.alpha,
48 beta: evt.beta,
49 gamma: evt.gamma
50 });
51 }, intervalObj.interval);
52 window.addEventListener('deviceorientation', deviceMotionListener, true);
53 }
54 else {
55 throw new Error('deviceMotion is not supported');
56 }
57 return handle.success();
58 }
59 catch (e) {
60 return handle.fail({ errMsg: e.message });
61 }
62};
63/**
64 * 监听设备方向变化事件。
65 */
66const onDeviceMotionChange = callback => {
67 callbackManager.add(callback);
68};
69/**
70 * 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。
71 */
72const offDeviceMotionChange = callback => {
73 callbackManager.remove(callback);
74};
75
76export { offDeviceMotionChange, onDeviceMotionChange, startDeviceMotionListening, stopDeviceMotionListening };
77//# sourceMappingURL=motion.js.map