Correct event registration in the 'PhoneGap + jQuery Mobile' application

偶尔善良 提交于 2019-12-03 10:32:41

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 () { 
        // ...
    });
});

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!