为什么我的JavaScript代码会过早启动?

时间:2012-02-22 19:05:10

标签: javascript android html dom cordova

我在onDeviceReady中添加了一个事件监听器来监听后退按钮事件,并在按下时使用stopWatch进行响应。但是,它会在应用程序启动时响应。

    <!DOCTYPE html>
<html>
  <head>
    <title>UNH BSApp</title>

    <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
    <script type="text/javascript" charset="utf-8">

    // The watch id references the current `watchAcceleration`
    var watchID = null;

    // Wait for PhoneGap to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    //
    function onDeviceReady() {
        document.addEventListener("backbutton", stopWatch(), false);
        startWatch();
    }

    // Start watching the acceleration
    //
    function startWatch() {
        document.addEventListener("menubutton", stopWatch(), false);
        // Update acceleration every 0.1 seconds
        var options = { frequency: 10 };

        watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
    }

    // Stop watching the acceleration
    //
    function stopWatch() {
        alert("Hello!");
        if (watchID) {
            navigator.accelerometer.clearWatch(watchID);
            watchID = null;
        }
    }

    // onSuccess: Get a snapshot of the current acceleration
    //
    function onSuccess(acceleration) {
        var element = document.getElementById('accelerometer');
        element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
                            'Acceleration Y: ' + acceleration.y + '<br />' +
                            'Acceleration Z: ' + acceleration.z + '<br />' +
                            'Timestamp: '      + acceleration.timestamp + '<br />';
    }

    // onError: Failed to get the acceleration
    //
    function onError() {
        alert('onError!');
    }

    </script>
    <style>
        #start {
            display:block;
            border:solid;
        }
    </style>
  </head>
  <body>
    <div id="accelerometer">Waiting for accelerometer...</div>
    <div id="start">Start</div>
  </body>
</html>

2 个答案:

答案 0 :(得分:4)

 document.addEventListener("menubutton", stopWatch(), false);

立即调用stopWatch函数。你想要这样的东西:

 document.addEventListener("menubutton", stopWatch, false);
                                                 ^^ no parens!

答案 1 :(得分:0)

从侦听器的设置中删除() - 这是调用函数而不是将其作为参数传递:

document.addEventListener("menubutton", stopWatch, false);