UNPKG

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