jQuery Mobile “pagebeforechange” being called twice

隐身守侯 提交于 2020-01-13 09:32:10

问题


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.


回答1:


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 ) { ...



回答2:


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.




回答3:


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

if data.toPage is set to a string, the event indicates that navigation is about to commence.

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




回答4:


If you read jquery mobile documentation https://api.jquerymobile.com/pagebeforechange/ , it says it is called twice, once data.toPage being url to new page, second time data.toPage being already jquery object of new page.



来源:https://stackoverflow.com/questions/8761859/jquery-mobile-pagebeforechange-being-called-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!