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

自闭症网瘾萝莉.ら 提交于 2019-12-04 16:25:56

问题


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:

  • PhoneGap v1.2
  • jQuery Mobile v1.0rc2
  • Eclipse v3.7.1

回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/8275313/correct-event-registration-in-the-phonegap-jquery-mobile-application

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