Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  74] [ 6]  / answers: 1 / hits: 22290  / 10 Years ago, sat, august 16, 2014, 12:00:00

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)
},


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)
},

More From » events

 Answers
34

As per the cordova documentation




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




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>

[#69758] Thursday, August 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;