JQuery Mobile "pagebeforechange" called twice

I have the following listener configured for "pagebeforechange" (very similar to the native JQuery Mobile Documentation code) and a link on the home page 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 the JavaScript console and click on the link, I see the following:

 showProduct being called. showProduct being called. 

It seems that I can not understand anything about why he was called twice. I saw other errors when vclicks are logged twice due to a click on the edge, but this makes no sense as it relies on the actual page change.

+6
source share
4 answers

Since you are attached to $ (the document) and use a multi-page layout

I think jQM loads the document several times (just a hunch)

Switch to pageId page, for example:

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

to

 $('#pageId').bind( "pagebeforechange", function( e, data ) { ... 
+6
source

Maybe a little late, but here is my educated guess:

Any page change event triggers two transitions, one “forward” (page change) and one “backward” (hehe). If you move forward, hashChange is blocked; if you move backward, it is the other way around.

Check out the jqm source code and check the ignoreNextHashChange property.

This is responsible for blocking hashChange when moving forward, otherwise you will go back and forth.

I think your function fires twice because both events are fired from within changePage and hashChange.

If that were the case, JQM would have to block the hash hash record before firing this event.

+4
source

It is called twice by design. http://api.jquerymobile.com/pagebeforechange/

if data.toPage set to a string, the event indicates that the start of navigation will begin.

if data.toPage set to a jQuery object, the event indicates that the landing page is loaded.

+3
source

If you read the jquery mobile documentation https://api.jquerymobile.com/pagebeforechange/ , it says that it is called twice as soon as data.toPage is the URL of the new page, the second time data.toPage is already the jquery object of the new pages.

-1
source

Source: https://habr.com/ru/post/905330/


All Articles