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!
Archived Comments
If you're trying to capture an event that may occur before or after device ready you should be able to work around it using `addStickyDocumentEventHandler`, an undocumented (?) cordova method -- I believe it's what's used for 'deviceReady'. I used Jamie Sutherland's method of adding a sticky document event handler Eddy Verbruggen's Custom Url Scheme plugin: https://medium.com/angularj... .
You should be able to do a similar catch-rethrow pattern to listen for events before `deviceready`, but instead of firing the event in 'handleupenurl', fire it in your 'deviceready' listener. Don't forget to remove, then re-add the sticky listener after you've 'caught' the event though!
Raymond,
thanks for the blog post. This is a constant issue for newbies on the forums. I'm very happy to have this blog to point to.
Jesse
Glad my mistakes help. :)
Hi Raymond,
this is just to let you know some of us on the Google Group have put together
Top Mistakes by Developers new to Cordova/Phonegap
https://github.com/jessemon...
This blog post is being referenced. Thanks for writing it.
Jesse
I have some comments on this - shall I file issues or reply here?
Either way. Or, I'd be happy to modify the document, or make additions, if you like. Jesse