In a plugin that I am currently authoring, I am using a function to check whether the device provides gyroscopic data. Although intuitively this can be easily resolved by checking the value of window.DeviceOrientationEvent
, i.e.:
if (window.DeviceOrientationEvent) {
// Ok, device orientation event listening is supported!
}
…this statement also resolves true when on a device with no functional gyroscope, i.e. Google Chrome on a laptop. The event data returned for alpha, beta and gamma are, however, null
. Basically, the window.DeviceOrientationEvent
does not tell me if there is gyroscopic data available, but only informs me if the browser/user-agent supports the event.
Therefore, not only do I have to check for support for the event, but also have to cross verify the value of alpha, beta or gamma such that they are not null. The best way I could check is using promises, which I feel a bit cumbersome and long-winded:
var check = {
// Does it have a working gyroscope?
gyroscope: function() {
var d = new $.Deferred(),
handler = function(e) {
d.resolve({
alpha: e.alpha,
beta: e.beta,
gamma: e.gamma
});
// Listen to device orientation once and remove listener immediately
window.removeEventListener('deviceorientation', handler, false);
};
window.addEventListener('deviceorientation', handler, false);
return d;
}
}
// Wait for gyroscope data
$.when(check.gyroscope()).done(function(r) {
if(r.alpha === null && r.beta === null && r.gamma === null) {
console.log('Device has no functional gyroscope.');
} else {
console.log('Device has functional gyroscope.')
}
});
I am wondering if there is a cleaner way to write this code?