popstate HTML 5 event being fired multiple times
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:
- Page loaded
- onclick will execute loadNextBackInPage()
- Start a $.post() Request and fire "callBackFunctionLoadNextBackInPage" on completion
- pushState()
- Register an event listener for "popstate"
- 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');
}
精彩评论