How can I check if a cord is ready if the deviceready event is already running?

In the cordova application example via cordova create ... , the following code listens for the deviceready event:

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

This is good, but what happens when an event leaves before I can listen to it? As an example, replace the code from the sample application (see above) as follows:

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

In this example, this.onDeviceReady is never called. There would be no better and more reliable way to check if the cordova is ready? Something like that:

 bindEvents: function() { setTimeout(function () { if (window.cordovaIsReady) { this.onDeviceReady() } else { document.addEventListener('deviceready', this.onDeviceReady, false); } }, 2000) }, 
+7
javascript events cordova ready
source share
2 answers

According to the cordova documentation

The deviceready event behaves somewhat differently than others. Any event handler registered after deviceready event fires has a callable call.

As you can see if there is any AFTER event handler attached that was started by deviceready, it will be called immediately .
In the setTimeout function, this one no longer points to the intended object; the context is different. Therefore, your handler will never be called. You can try the code below by putting it in your <head> , where I use global functions / variables (while avoiding this contextual issue for simplicity). This should show you a warning.

 <script> function onDeviceReady () { alert("Calling onDeviceReady()"); } setTimeout(function () { document.addEventListener('deviceready', onDeviceReady, false); }, 9000); </script> 
+13
source share

frank answer really works. But the right way to handle this is not to add a timeout.

The deviceready event deviceready will be created at boot time of the DOM. Therefore, to use the event, we must wait until DOMContentLoaded . after that we can add a listener to the deviceready event

 document.addEventListener("DOMContentLoaded", function() { //alert("Calling DOMContentLoaded"); document.addEventListener('deviceready', function(){ //alert("Calling onDeviceReady()"); callFirebase(); }, false); }); 
-one
source share

All Articles