I am trying to understand the page events in jQueryMobile navigation, but I found some very weird behaviour, as some event handlers get called several times:
I have two pages: home.html and disclaimer.html. Both contain the same header:
<head>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/events.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
</head>
On the page home.html is a link:
<section data-role="page" id="home">
<a href="#" id="test">Test</a>
</section>
And in the file events.js is the following code:
var i = 0;
$(document).on('pageinit', 'section#home', function(event) {
console.log(i++, 'pageinit');
$('a#test').on('click', function() {
console.log(i++, 'click pageinit');
});
});
$(document).on('pagebeforeshow', 'section#home', function(event) {
console.log(i++, 'pagebeforeshow');
$('a#test').on('click', function() {
console.log(i++, 'click pagebeforeshow');
});
});
Then I do the following steps:
- Navigate to home.html (http)
- Click the link
- Go to disclaimer.html (ajax)
- Go to home.html (ajax)
- Click the link
With the following console output:
0 "pageinit" // step 1
1 "pagebeforeshow"
2 "click pageinit" // step 2
3 "click pagebeforeshow"
4 "pagebeforeshow" // step 4
5 "click pageinit" // step 5
6 "click pagebeforeshow"
7 "click pagebeforeshow"
Makes sense, right? But now the weird part. When I change the order in which I visit the pages: the behaviour changes.
- Navigate to disclaimer.html (http)
- Go to home.html (ajax)
- Click the link
- Go to disclaimer.html (ajax)
- Go to home.html (ajax)
- Click the link
Console output:
0 "pageinit" // step 2
1 "pagebeforeshow"
2 "click pageinit" // step 3
3 "click pagebeforeshow"
4 "pageinit" // step 5
5 "pagebeforeshow"
6 "click pageinit" // step 6
7 "click pagebeforeshow"
Which is weird, because I would expect the 6th and 7th result to have been duplicated.
Sorry for the very long question. I hope someone can explain to me exactly what is happening and if this is expected behaviour?
tldr; Where do you listen for (click) events in jQueryMobile?