I am trying to define the correct way to register both initialization events (jQuery-style) for PhoneGap and jQuery Mobile in an Android application.
After studying the documentation, I came up with the following:
$('#index-page').live('pageinit', function () { // <-- fires
$(document).bind('deviceready', function () { // <-- !fires
// ...
});
});
The "outer" event (pageinit
) fires and the "inner" (deviceready
) does not...
Although, this type of event registration works perfectly:
window.addEventListener('load', function () {
document.addEventListener('deviceready', function () {
// ...
}, false);
}, false);
Can anybody explain what's wrong with the first type of event registration? What type is better?
Prerequisites:
I find the use of deferred objects cleaner/safer in this case. This is what I usually do:
var jqmReady = $.Deferred();
var pgReady = $.Deferred();
// jqm ready
$(document).bind("mobileinit", jqmReady.resolve);
// phonegap ready
document.addEventListener("deviceready", pgReady.resolve, false);
// all ready :)
$.when(jqmReady, pgReady).then(function () {
// do your thing
});
I would go farther with Michael's example, and trigger a custom 'PG_pageinit' JavaScript event. This will trigger after both events ('pageinit', 'deviceready') have been fired. This way, you only need to change the name of the registered event at your (already written) external JavaScript files.
So, using Michael's code (with a minor change from the 'mobileinit' event to 'pageinit'):
var jqmReady = $.Deferred(),
pgReady = $.Deferred();
// jqm page is ready
$(document).bind("pageinit", jqmReady.resolve);
// phonegap ready
document.addEventListener("deviceready", pgReady.resolve, false);
// all ready, throw a custom 'PG_pageinit' event
$.when(jqmReady, pgReady).then(function () {
$(document).trigger("PG_pageinit");
});
And on your other JavaScript files, whenever you want to register this new event, use this:
$(document).bind("PG_pageinit", function(){
alert('PG_pageinit was just fired!');
// do your thing...
});
Tested on Android 2.3, cordova 1.9.0
Please stick with the last one because this is recommended by PhoneGap, your first approach probably isn't working because you are binding deviceready
too late (ie: it is already fired before your bind). Thats because pageinit
is fired relatively late.
What you can do is the jQuery way:
$(window).load(function() {
$(document).bind('deviceready', function () {
// ...
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With