/*
* PhoneGap Essential Training by ninghao.net
*/
var app = {
// 应用构造器
initialize: function() {
this.bindEvents();
var watchID = null;
},
// 绑定事件监听器
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready 事件处理
onDeviceReady: function() {
app.receivedEvent('deviceready');
var startWatch = document.getElementById('startwatch');
var stopWatch = document.getElementById('stopwatch');
startWatch.addEventListener('touchstart', app.startWatch, false);
stopWatch.addEventListener('touchstart', app.stopWatch, false);
},
startWatch: function() {
var options = {
frequency: 1000
};
app.watchID = navigator.accelerometer.watchAcceleration(
app.onSuccess,
app.onError,
options
);
},
stopWatch: function() {
if(app.watchID) {
navigator.accelerometer.clearWatch(app.watchID);
app.watchID = null;
}
},
onSuccess: function(acceleration) {
var accelerationValue = document.getElementById('acceleration-value');
accelerationValue.innerHTML =
'Acceleration X: ' + acceleration.x + '<br>' +
'Acceleration Y: ' + acceleration.y + '<br>' +
'Acceleration Z: ' + acceleration.z + '<br>' +
'Timestamp: ' + acceleration.timestamp + '<br>';
},
onError: function(error) {
console.log(error.code);
},
// 接收到事件以后更新 DOM
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};