如何防止PhoneGap设备就绪功能执行两次

时间:2013-04-03 18:55:34

标签: javascript cordova ripple

在我的应用程序中,我在index.html中加载脚本文件时调用函数init()。以下代码应验证cordova是否已成功加载(对于现代手机,特别是旧款黑莓手机),并随后调用onDeviceReady函数。

我改编了Jamie Munro的“20 Recipes for Programming PhoneGap”中的代码,但它没有正常工作(intervalID只在本地可用)。后来发现onDeviceReady函数被多次调用...我尝试了几种方法来阻止它,但是即使是下面的例子也没有在ripple模拟器中运行时的技巧。

我错过了什么?

var count = 0

function init() {

    // Add an event listener for deviceready
    document.addEventListener("deviceready", onDeviceReady, false);

    // Older versions of Blackberry < 5.0 don't support
    // PhoneGap's custom events, so instead we need to perform
    // an interval check every 500 milliseconds to see whether
    // PhoneGap is ready.  Once done, the interval will be
    // cleared and normal processing can begin.
    intervalID = window.setInterval(function() {
        if (window.cordova) {
            window.clearInterval(intervalID);
            onDeviceReady();
        }
    }, 1000);
}

function onDeviceReady() {

    if(count == 0) {
        count += 1;
        alert('The device is now ready');
    }

}

1 个答案:

答案 0 :(得分:1)

Ripple似乎加载页面一次以捕获URL,然后在iframe中再次加载它以在模拟手机上显示它。因此,所有内容的两个副本都会加载到不同的文档中。由于我为包括按钮点击在内的所有内容获得了两个事件,因此我的代码的两个副本似乎都会收到相同的事件。或者也许Ripple会为另一个重复它。但是由于代码在不同的文档和不同的范围内,它们似乎并没有互相干扰(至少它们不适合我)。也许其他人可以对我认为我发现的内容提供更好,更有见识的解释。