且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery mobile $ .mobile.changePage在iPhone上不能正常工作PhoneGap

更新时间:2022-10-17 12:07:46

如果任何人正在寻找这个问题的快速解决方法。尝试使用window.setTimeout向程序执行添加延迟。请参阅上面的问题代码。


I was having an annoying problem that had me stumped for about two days.

I developed a PhoneGap application using jQuery mobile for the framework. I initially developed it on Android and all worked fine.

Now, it's supposed to be cross-platform but when I brought it over to iPhone, it wouldn't get past the splash screen. I followed a few red herrings but eventually managed to zone in on the problem in JavaScript.

It was a call to $.mobile.changePage early on in the program execution that was causing the problem. Appears to be some kind of race condition because when I commented out the offending line of code, it got past the splash screen and then if I ran the statement remotely from the Safari development console, it worked okay. To add to my frustration, it even worked okay in the Safari browser on the iPad but just not within the PhoneGap app which was even more strange.

I followed some advice to use setTimeout as a workaround which I got from a jQuery mobile github issue page here: https://github.com/jquery/jquery-mobile/issues/3190

This made it work (thankfully!!). However, am I doing something wrong? I feel there should be a better solution than merely adding a delay to the program execution.

Here is the code:

$(document).on('pageinit', '#home', onHomePageInit);     

function onHomePageInit() {
    $("#home").on("pageshow", checkTokenAndSync());
}

function checkTokenAndSync() {
    // check for stored values
    var storedId = window.localStorage.getItem('id');
    var tokenValue = window.localStorage.getItem('token');

    if(storedId == null || tokenValue == null) {
        // no token value found, direct user to login screen to obtain one

        // This doesn't work.  Need to use setTimeout as below
        // $.mobile.changePage("#loginDialog");

        window.setTimeout(changeToLoginDialog, 1000);
    }   
}

function changeToLoginDialog() {
    $.mobile.changePage("#loginDialog");
}

I'm going to add a comment to that github issue page.

In case anyone is looking for a quick-fix workaround to this problem. Try using window.setTimeout to add a delay to the program execution. See question above for code.