I have a single file for each page and i am trying to implement the pageinit event handler on every page (I think what belongs strictly to one page, should be declared there) as shown below:
<body>
<div id="myPage" data-role="page">
<!-- Content here -->
<script type="text/javascript">
$("#myPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
The event is bound properly to the page, so the code is executed but - now my problem - if i go to another page and return later on the pageinit event will be executed twice. I think that is because the .live method binds the pageinit event again to the page. But shouldn't the pageinit event only called once at page initialization? What I am missing here?
I think its probably best to move your JavaScript code into another file as while your navigating around your site jQuery Mobile may cleanup (read: delete from DOM) that
myPage
page and therefore will have to load it in again and hense rerun that same block of code you defined and bind 2 listeners for thepageinit
event.Thats basically why they suggest using the
live
oron
functions however it falls over if you include the binding code on the page ;)However if you insist on having your code placed on a per page basis than use
bind
instead oflive
.Ref: http://jquerymobile.com/demos/1.0/docs/pages/page-cache.html