@tarojs/taro-h5
Version:
Taro h5 framework
77 lines (74 loc) • 2.31 kB
JavaScript
import throttle from 'lodash-es/throttle';
import { CallbackManager, MethodHandler } from '../../utils/handler.js';
const callbackManager = new CallbackManager();
let deviceMotionListener;
const INTERVAL_MAP = {
game: {
interval: 20,
frequency: 50
},
ui: {
interval: 60,
frequency: 16.67
},
normal: {
interval: 200,
frequency: 5
}
};
/**
* 停止监听设备方向的变化。
*/
const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete });
try {
window.removeEventListener('deviceorientation', deviceMotionListener, true);
return handle.success();
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
};
/**
* 开始监听设备方向的变化。
*/
const startDeviceMotionListening = ({ interval = 'normal', success, fail, complete } = {}) => {
const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete });
try {
const intervalObj = INTERVAL_MAP[interval];
if (window.DeviceOrientationEvent) {
if (deviceMotionListener) {
stopDeviceMotionListening();
}
deviceMotionListener = throttle((evt) => {
callbackManager.trigger({
alpha: evt.alpha,
beta: evt.beta,
gamma: evt.gamma
});
}, intervalObj.interval);
window.addEventListener('deviceorientation', deviceMotionListener, true);
}
else {
throw new Error('deviceMotion is not supported');
}
return handle.success();
}
catch (e) {
return handle.fail({ errMsg: e.message });
}
};
/**
* 监听设备方向变化事件。
*/
const onDeviceMotionChange = callback => {
callbackManager.add(callback);
};
/**
* 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。
*/
const offDeviceMotionChange = callback => {
callbackManager.remove(callback);
};
export { offDeviceMotionChange, onDeviceMotionChange, startDeviceMotionListening, stopDeviceMotionListening };
//# sourceMappingURL=motion.js.map