开发者

popstate HTML 5 event being fired multiple times

开发者 https://www.devze.com 2023-03-08 15:25 出处:网络
Hi i am using the following code to load a part of page dynamically using jquery loadNextBackInPage_URL = null;

Hi i am using the following code to load a part of page dynamically using jquery

loadNextBackInPage_URL = null;
function callBackFunctionLoadNextBackInPage(data)
{
    //alert(data);
    $("#left").fadeTo(100,1);
    var data = $(data).find( '#left' );
    $("#left").html(data);
    if(supports_history_api())
    {
        history.pushState(null, null, loadNextBackInPage_URL);
        window.addEventListener("popstate", function(e) {
        alert('s');
        loadNextBackInPage(location.pathname);
        });
    }
    else
    {

    }
}
function loadNextBackInPage(url,parm)
{
    //alert(url);
    loadNextBackInPage_URL = url;
    $("#left").fadeTo(100,.2);
    $.post(url,parm,callBackFunctionLoadNextBackInPage,'html');


}

The loading part and even changing the browser URL is开发者_JAVA技巧 working. but why is the PoP state function being fired multiple times?

I call loadNextBackInPage() originally through an onclick function.


I got it solved from here in codingforums

think you keep adding "popstate" listeners over and over ...

Program logic:

  1. Page loaded
  2. onclick will execute loadNextBackInPage()
  3. Start a $.post() Request and fire "callBackFunctionLoadNextBackInPage" on completion
  4. pushState()
  5. Register an event listener for "popstate"
  6. When "popstate" fires, execute loadNextBackInPage() and return to step 2

So step 4 will be executed over and over which will register new event listeners. Every time "popstate" fires all the event listeners will execute

Try to move the addEventListener method call out of this loop

So from those i derived a workaround and also corrected location.pathname to location.href

The corrected code:

loadNextBackInPage_URL = null;
popEventListnerAdded = false;


function callBackFunctionLoadNextBackInPage(data)
{
    //alert(data);
    $("#left").fadeTo(100,1);
    var data = $(data).find( '#left' );
    $("#left").html(data);
    if(supports_history_api())
    {
        history.pushState(null, null, loadNextBackInPage_URL);  
        if(!popEventListnerAdded) {
            window.addEventListener("popstate", function(e) {
            loadNextBackInPage(location.href);
            });
            popEventListnerAdded = true;
        }

    }
    else
    {

    }
}
function loadNextBackInPage(url,parm)
{
    //alert(url);
    loadNextBackInPage_URL = url;
    $("#left").fadeTo(100,.2);
    $.post(url,parm,callBackFunctionLoadNextBackInPage,'html');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消