在'PhoneGap + jQuery Mobile'应用程序中更正事件注册

Joh*_*Doe 15 android-2.2-froyo jquery-mobile cordova

我正在尝试定义在Android应用程序中为PhoneGapjQuery Mobile注册初始化事件(jQuery样式)的正确方法.

在研究了文档之后,我想出了以下内容:

$('#index-page').live('pageinit', function () { // <-- fires
    $(document).bind('deviceready', function () { // <-- !fires
        // ...
    });
});
Run Code Online (Sandbox Code Playgroud)

"外部"事件(pageinit)触发,"内部"(deviceready)不......

虽然,这种类型的事件注册工作完美:

window.addEventListener('load', function () {
    document.addEventListener('deviceready', function () {
        // ...
    }, false);
}, false);
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释第一种类型的事件注册有什么问题吗?什么类型更好?


先决条件:

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

Mic*_*lis 14

在这种情况下,我发现延迟对象的使用更清洁/更安全.这就是我通常做的事情:

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
});
Run Code Online (Sandbox Code Playgroud)


Roe*_*umi 7

我会继续迈克尔的例子,并触发一个自定义的'PG_pageinit'JavaScript事件.这将在两个事件('pageinit','deviceready')被触发后触发.这样,您只需要在(已编写的)外部JavaScript文件中更改已注册事件的名称.

所以,使用迈克尔的代码(从'mobileinit'事件到'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"); 
});
Run Code Online (Sandbox Code Playgroud)

在其他JavaScript文件中,只要您想注册此新事件,请使用以下命令:

$(document).bind("PG_pageinit", function(){
  alert('PG_pageinit was just fired!');    
  // do your thing...
});
Run Code Online (Sandbox Code Playgroud)

在Android 2.3,cordova 1.9.0上测试


Ger*_*ine 6

请坚持使用最后一个,因为这是PhoneGap推荐的,你的第一种方法可能不起作用,因为你的绑定deviceready太晚了(即:它已经在你的绑定之前被解雇).那是因为pageinit被解雇相对较晚.

你可以做的是jQuery方式:

$(window).load(function() {
    $(document).bind('deviceready', function () { 
        // ...
    });
});
Run Code Online (Sandbox Code Playgroud)