a0z0ra
a0z0ra

Reputation: 171

how to tell mobileinit to pause executing until json is loaded

How do I told jquerymobile to postpone executing mobileinit until DOM is loaded?

I'm trying to create pages on the fly using templates & JSON. My problem is that JSON takes too long to load and jquerymobile has finished mobileinit event!

Example code:

    $(document).bind("mobileinit", function(){
        console.log("mobileinit");

        // get JSON & set template... should wait until this is done!
        getData();

        //SWIPE SWIPE
        $('div[data-role="page"]').live("swipeleft", function(){
            var nextpage = $(this).next('div[data-role="page"]');
            // swipe using id of next page if exists
            if (nextpage.length > 0) {
                $.mobile.changePage(nextpage, 'slide');
            }
        });
        $('div[data-role="page"]').live("swiperight", function(){
            var prevpage = $(this).prev('div[data-role="page"]');
            // swipe using id of next page if exists
            if (prevpage.length > 0) {
                $.mobile.changePage(prevpage, 'slide', true);
            }
        });
        console.log("mobileinit done");
    });

Upvotes: 0

Views: 245

Answers (2)

Benny Johansson
Benny Johansson

Reputation: 771

You can use jQuery.Deferred() to accomplish this.

// Let's assume that getData returns a deferred.
function getData() {
    return $.get('your/request/url');
});

$(document).bind("mobileinit", function() {
    // Now you can use the deferred returned from the getData function.
    getData().done(function() {
        //SWIPE SWIPE
        $('div[data-role="page"]').live("swipeleft", function() {
            var nextpage = $(this).next('div[data-role="page"]');
            // swipe using id of next page if exists
            if (nextpage.length > 0) {
                $.mobile.changePage(nextpage, 'slide');
            }
        });
        $('div[data-role="page"]').live("swiperight", function() {
            var prevpage = $(this).prev('div[data-role="page"]');
            // swipe using id of next page if exists
            if (prevpage.length > 0) {
                $.mobile.changePage(prevpage, 'slide', true);
            }
        });
    });
}

Upvotes: 1

paulslater19
paulslater19

Reputation: 5917

Assuming the getData() function contains an $.ajax call, you'll need to put the reset of the init code within the success function of the getData()'s $.ajax call

Upvotes: 1

Related Questions