Roel
Roel

Reputation: 764

jQuery Mobile Not firing pageinit

Now, my question is 'simple' (the question is, the solution maybe not). I have a function that retrieves data using $.json(). The data has to be loaded into a <ul> using a function which is called from the 'pageinit'/'pageshow'. Though it does not load anything at all. BUT! When I refresh the page, it loads the pageinit completely without problems.

This is my jQuery;

$('#showsPage').bind('pageshow', function(event) {
    getShows();
});

/******* FUNCTIONS *********/
function getShows()
{
    // Loading.
    $.mobile.loading('show');

    // Load the data.
    $.getJSON("some url", function(json) {

        $("#listShows li").remove();

        $.each(json.data, function(index, show) {

            $("#listShows").append("<li><a href='#'>Stuff</a></li>");
            $("#listShows").listview('refresh');

            // Hide the loading.
            $.mobile.loading('hide');

        });
    });
}

Am I doing something drastically wrong? I have a pageinit running on a different page without problems.

Upvotes: 1

Views: 1164

Answers (1)

Jasper
Jasper

Reputation: 75993

Due to jQuery Mobile's AJAX handling of page transitions, you should delegate your event binding when binding to page-events, like pageinit or pageshow.

Here is an example:

$(document).on('pageshow', '#showsPage', getShows);

This will make sure that the binding does not occur until the #showsPage element is actually in the DOM.

Notice how you don't need an anonymous function if you aren't passing-in any arguments. In the case of not passing any arguments you can just pass the name of the function to the .on() method as the callback.

Note that this delegated event handler needs to be bound whenever a user refreshes a page or deep-links into your site, so I suggest placing it in an external script and including that script in the <head> of each document (just before the end </body> tag works too, just not inside a data-role="page" element) so that any page refresh won't break functionality on your site. Another method is to place code that is for a specific page inside the data-role="page" element so when it's brought into the DOM via AJAX, your code will be parsed by jQuery Mobile.

Upvotes: 3

Related Questions