Simply because pageshow
and pagehide
will fire on any page. In your code you haven't delegated the event to neither index or dialog. Those events are bound to document, so will fire on all pages to come.
If you do the below, you'll notice the difference.
$(document).on("pageshow", "#index", function () {
console.log("Page is shown");
});
It will only fire on index page (with id="index"
) when it is visible.
Update
In your code, you haven't attached pageshow
and pagehide
to specific pages. Both events fire on data-role="page"
and data-role="dialog"
when they are either visible or hidden.
In index.html, you have the below code.
$(document).on('pageshow', '#indexpage', function(event) {
console.log('pageshow index.html');
});
$(document).on('pagehide', '#indexpage', function(event) {
console.log('pagehide index.html');
});
On start-up, console log will print
pageshow index.html
When you move from index.html to dialog.html (via Ajax), console log will print
pagehide index.html
But before console log prints pagehide index.html
, the below code in dialog.html is loaded into DOM along with HTML and executed.
$(document).on('pageshow', '#dialogPage', function(event) {
console.log('pageshow dialog.html');
});
$(document).on('pagehide', '#dialogPage', function(event) {
console.log('pagehide dialog.html');
});
Therefore, pagehide
will fire twice when moving from index.html to dialog.html. Also, it will fire twice when moving from dialog.html back to index.html. At this moment, pageshow
will fire twice as well.
Console log will print the following:
Start-up
pageshow index.html
From index.html to dialog.html
pagehide index.html -> pagehide dialog.html -> pageshow index.html -> pageshow dialog.html
From dialog.html to index.html
pagehide index.html -> pagehide dialog.html -> pageshow index.html -> pageshow dialog.html
Solution:
Be specific when using pagebeforehide
, pagebeforeshow
, pagehide
and pageshow
events
$(document).on("pageshow", "#pageID", function () {
/* do something */
});