简体   繁体   中英

jQuery mobile pageshow event not firing on first $.mobile.changePage()

I'm writing a phonegap/jquery mobile app and have an issue I cant seem to solve.

When the app loads (device ready and jqm_mobile_init) fire and the app creates/opens a database and checks if a user is signed in (just a flag in the db). If so the app calls $.mobile.changePage("#home", {transition:"none"}); to redirect them to the "home" page.

Then on the "home" page pageshow event I grab a load of info from the db and append it to a listview within the home page.

However, the first time this runs (with the $.mobile.changePage event) the pageshow event isn't trigged (so none of my data gets appended to the listview). If I navigate around the app and then visit the page the data shows fine. This only happens when using $.mobile.changePage to change to the home page.

How can I make pageshow() fire on $.mobile.changePage? or is there another way to do it?

Heres my code:

/************************************************
Try to create/open the DB, if not catch the error
***********************************************/
try {
    if (!window.openDatabase) {
        alert('not supported');
    } else {
        var shortName = 'test';
        var version = '1.0';
        var displayName = 'test Database';
        var maxSize = 200000; // in bytes
        // database instance in db.
        var db = openDatabase(shortName, version, displayName, maxSize);

        // Create tables
        createTables(db);

        // Check if there is a signedin user
        isUserSignedInQuery(db);

    }
} catch(e) {
    // Error handling code goes here.
    if (e == 2) {
        // Version number mismatch.
        alert("Invalid database version.");
    } else {
        alert("Unknown error "+e+".");
    }
    return;
}

// Universal null/blank data handler
function nullDataHandler(transaction, results) { }

// Universal error callback
function errorHandler(error) {
    //alert("Error processing SQL: " +error.message+ " Error Code: " +error.code);
}

// Create tables if dont already exist
function createTables(db) {
    db.transaction(
        function (transaction) {

            // create tables
    }
    );
}

/**********************************************************************************************
Check if there is a signed in user, if so redirect to listings page, if not display login page
**********************************************************************************************/

function isUserSignedInQuery(db) {
    db.transaction(
        function (transaction) {
            transaction.executeSql("SELECT * FROM USERS WHERE signedIn=1;",
            [], // array of values for the ? placeholders
            isUserSignedInDataHandler, errorHandler);
        }
    );
}

function isUserSignedInDataHandler(transaction, results) {
    // Handle the results
    if (results.rows.length > 0) {
        //console.log("someones logged in!");

        // Assign signed in user to global var
        console.log("logged in user = " + results.rows.item(0).id);
        window.currentSignedInUserId = results.rows.item(0).id;

        $.mobile.changePage( "#home", { transition: "none"} );
    } else {
        $.mobile.changePage( "#login", { transition: "none"} );
    }
}


/**********************************************************************************************
Sign in page:
**********************************************************************************************/

function doesSigningInUserAlreadyExistQuery(db) {
    db.transaction(
        function (transaction) {
            transaction.executeSql("SELECT * FROM USERS WHERE username='"+usernameValue+"' ORDER BY id LIMIT 0,1;",
            [], // array of values for the ? placeholders
            doesSigningInUserAlreadyExistDataHandler, errorHandler);
        }
    );
}

function doesSigningInUserAlreadyExistDataHandler(transaction, results) {

    // User exists, sign them in.
    if (results.rows.length > 0) {

        //console.log("user exists");

        // Find number of rows
        var len = results.rows.length;
        //console.log(len);

        for (var i=0; i<len; i++){
            //console.log(results.rows.item(i));

            db.transaction(
                function (transaction) {
                    transaction.executeSql('UPDATE USERS SET signedIn = 1 WHERE username="'+usernameValue+'"');
                }               
            );

            // Assign signed in user to global var
            window.currentSignedInUserId = results.rows.item(0).id;

            // Redirect to home/listings page
            $.mobile.changePage( "#home", { transition: "slidefade"} );
        }

    // User is new, create them and sign them in
    } else {

        db.transaction(
            function (transaction) {
                transaction.executeSql('INSERT INTO USERS (username, password, userId, defaultHandler, autoSync, updateCaseTypes'
                +', updateHistorical, updateFavorite, signedIn) '
                +'VALUES ("'+usernameValue+'", "eclipse", "userid321", "Another User", 1, 1, 1, 1, 1);', [],
                function (transaction, resultSet) {
                    if (!resultSet.rowsAffected) {
                        // Previous insert failed.
                        alert('No rows affected!');
                        return false;
                    }
                    alert('insert ID was '+resultSet.insertId);

                    //Assign signed in user to global var
                    window.currentSignedInUserId = resultSet.insertId;
                });
            }               
        );

        // Redirect to home/listings page
        $.mobile.changePage( "#home", { 
            reloadPage: true,
            transition: "slidefade"} );

    }
}

$('#login').live('pageshow', function(event) {

    console.log(window.currentSignedInUserId); // This is empty - global var not working

    // Should this be tap??????? Find out. -----------
    $('a#signIn').click(function() {

        // Get values of all fields & buld vars
        var username = $('#login-username');
        var password = $('#login-password');

        // Check if fields are empty
        if( !username.val() ) {
              username.addClass('empty');
              $('label.login-username').addClass('blank');
            }
            if( !password.val() ) {
              password.addClass('empty');
              $('label.login-password').addClass('blank');
            }

            // If both not empty, check if user exists, if so sql update if not sql insert
            if (username.val() && password.val()) {

                // Get username
                usernameValue = username.val();

                // Run function
                doesSigningInUserAlreadyExistQuery(db);

            }

    });
});


$('#home').live('pageshow', function(event) {

    console.log("Page show fired on recordings page");

    db.transaction(getRecordingsQuery, getRecordingsDataHandler, errorHandler);

            // get stuff, loop through it and append

        // Refresh the list to add JQM styles etc
        $('#recordings-list').listview('refresh');

    }

});

I've managed to resolve it, its not really a proper fix but it works at the expense of a screen flicker whilst the screen refreshes.

If it helps anyone, I added allowSamePageTransitions: true which solved the issue (at the expense of a flicker).

You should be using on() instead of live() . live() has been deprecated.
Have you tried putting it in the beforepageshow instead of pageshow ? It seems like a better place to put data gathering/dynamic page element generation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM