如果deviceready事件已经触发,如何检查cordova是否准备就绪? [英] How can I check if cordova is ready if the deviceready event has already fired?

查看:4178
本文介绍了如果deviceready事件已经触发,如何检查cordova是否准备就绪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在示例应用程序cordova通过 cordova create ... 提供,以下代码监听 deviceready 事件:

In the example app cordova provides through cordova create ..., the following code listens to the deviceready event:

bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},

这很好,但是当事件被触发时,有时间听吗?例如,使用以下代码替换示例应用程序(上面)中的代码:

This is nice, but what happens when the event is fired before I've had time to listen for it? As an example, replace the code from the example app (above) with the following:

bindEvents: function() {
    setTimeout(function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    }, 2000)
},

在此示例中,从不调用this.onDeviceReady。会不会有更好,更可靠的方法来检查cordova是否准备好了?像这样:

In this example, this.onDeviceReady is never called. Would there not be a better, more reliable way to check if cordova is ready? Something like this:

bindEvents: function() {
    setTimeout(function () {
        if (window.cordovaIsReady) {
            this.onDeviceReady()
        } else {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        }
    }, 2000)
},


推荐答案

cordova文档


deviceready事件与其他事件有所不同。任何在deviceready事件触发后注册的
事件处理程序都会立即调用
回调函数。

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.

查看是否有任何事件处理程序附加在 AFTER 后,设备已触发,将立即调用

setTimeout 不再指向预期对象,上下文不同。因此,您的处理程序将永远不会被调用。

您可以通过将它放在< head> 标记中来尝试以下代码,函数/变量(为了简单起见,避免了上下文问题)。这应该会向您显示警报。

As you can see if any event Handler is attached AFTER the deviceready has fired it will be called immediately.
In a setTimeout function this is a no longer pointing to the intended object, the context is different. Therefore your handler will never be called.
You can try the below code by placing it in your <head> tag, where I am using global functions/variables (avoiding the this context issues for sake of simplicity). This should show you an alert.

<script>
    function onDeviceReady () {
     alert("Calling onDeviceReady()");
    }

    setTimeout(function () {
            document.addEventListener('deviceready', onDeviceReady, false);
    }, 9000);
</script>

这篇关于如果deviceready事件已经触发,如何检查cordova是否准备就绪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆