Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Mobile "pagebeforechange" being called twice

I have the following listener set up for "pagebeforechange" (very similar to the jQuery Mobile Documentation's own code) and a link on the home page that is calling http://localhost/#product?id=255979

//Bind Listener for Product Details
$(document).bind( "pagebeforechange", function( e, data ) {
    //Only Run If Site is Initialized
    if( ajaxSite.options.initialized ) {
        if ( typeof data.toPage === "string" ) {
            var u = $.mobile.path.parseUrl( data.toPage ),
                pl = /^#product/;

            if ( u.hash.search(pl) !== -1 ) {
                console.log("showProduct being called.");
                ajaxSite.showProduct( u, data.options );
                e.preventDefault();
            }
        }
    }
});

When I open up the JavaScript console and click the link I am seeing the following:

showProduct being called.
showProduct being called.

I can't seem to find anything about why it would be getting called twice. I have seen other errors where vclicks get registered twice due to edge-clicking, but this doesn't make any sense since it is relying on the actual page change.

like image 866
Jack Avatar asked Jan 06 '12 17:01

Jack


2 Answers

Since you're binding to the $(document) and using a Multi-page layout

  • http://jquerymobile.com/demos/1.0/docs/pages/index.html

I think jQM is loading the document multiple times (Just a hunch)

Switch to using the pageId instead, example:

$(document).bind( "pagebeforechange", function( e, data ) { ...

to

$('#pageId').bind( "pagebeforechange", function( e, data ) { ...
like image 191
Phill Pafford Avatar answered Sep 28 '22 17:09

Phill Pafford


Maybe a little late, but here's my educated guess:

Any pagechange event triggers two transitions, one "forward" (pagechange) and one "backward" (hashchange). If you go forward, the hashChange is blocked, if you backward, it's the other way around.

Look into the jqm source code and check the ignoreNextHashChange property.

This is responsible for blocking the hashChange on forward transitions, otherwise you'd be going back and forth.

I guess your function is firing twice, because both events are both triggered from inside changePage and hashChange.

If that was the case, JQM would have to block the hashChange rountine before triggering this event.

like image 29
frequent Avatar answered Sep 28 '22 17:09

frequent