-1

Here is my simplified code which has two pages which link to each other. The result is the page2 count alert always says there is one #page2 div in the DOM. However pagecreate fires for each time that page2.html has been referenced. First time is 1, second time is 2, and so on...

Can someone explain what is going on and how to get one pagecreate event for page2?

index.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="jquery.mobile-1.0.1.min.css" />
    <script src="jquery-1.6.4.min.js"></script>
    <script src="jquery.mobile-1.0.1.min.js"></script>
</head>
<body>
    <div data-role="page">
        <div data-role="content">
            <h3>In Index Page</h3>
            <a href="page2.html" data-role="button">Go To Page2</a>
        </div>
     </div>
</body>
</html>


page2.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div id="page2" data-role="page">
        <div data-role="content">
            <a href="index.html" data-role="button">Back</a>
        </div>
        <script type="text/javascript">
            alert("page2 count is " + $("#page2").length);
            $("#page2").live('pagecreate',function(event, ui) {
                alert("in page2 on pagecreate");
            });
        </script>
    </div>
</body>
</html>

Thanks,
-- Ed
emsieja
  • 186
  • 1
  • 2
  • 10

1 Answers1

0

jQM loads subsequent pages into the same DOM (page) using a debugger/dev tools with Chrome you can easily see this happen.

In subsequent pages it pulls in anything between your tags, but ignores everything else, you could have JS in your or other pages and it'd still only pull in page2.

What exactly is happening with you is that when you load #page2 the first time it properly adds a live event to #page2, then you navigate to index.html, but #page2 remains in your DOM. Now when you goto #page2 again, it will run your JS again

 $("#page2").live('pagecreate',function(event, ui) {
        alert("in page2 on pagecreate");
 });

This binds your alert again, and 2 events fire, next time 3 will fire.

The way you're supposed to do it is load all your JS at the start and listen for the pageinit/pageshow, see my other post: https://stackoverflow.com/a/9085014/737023

Or if you have any questions ask here

Community
  • 1
  • 1
Clarence Liu
  • 3,874
  • 2
  • 25
  • 29
  • Yes, this helps me understand it much better now. To fix my problem I simply moved the live binding out of page2.html and into the header script in index.html -- now the alert says 1 #page2 div element and pagecreate fires once each time page2.html is referenced. Thanks! – emsieja Mar 21 '12 at 17:15