FYI - Cordova events must be run after deviceReady

In all of my work on various Cordova projects, I've only rarely needed to make use of the various events supported by the platform. Last night I needed to add some code to handle the back button. The docs clearly tell you to register your handler after deviceReady has fired:

To override the default back-button behavior, register an event listener for the backbutton event, typically by calling document.addEventListener once you receive the deviceready event.

But obviously I know better. I mean - it's an event, right? So it shouldn't matter when we add the listener. Sure, if the user hits the back button before deviceReady fires, I assume my handler won't run, but it should be safe to register it whenever, right?

Nope.

After bringing this up in the Slack channel, @devgeeks pointed out this little snippet from the Cordova JavaScript library:

/**
 * Intercept calls to addEventListener + removeEventListener and handle deviceready,
 * resume, and pause events.
 */
var m_document_addEventListener = document.addEventListener;
var m_document_removeEventListener = document.removeEventListener;
var m_window_addEventListener = window.addEventListener;
var m_window_removeEventListener = window.removeEventListener;

Essentially, Cordova modifies the default event listener in your web view so it can actually handle some of those special events. So, I guess the point of this post is - yes - it really does matter where you add your event handlers in regards to the events Cordova gives you access to!

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.

See Also