Reputation: 55962
I am attaching a click event to an image on my page.
$('.ui-block-b img').click(function(event) {}
I am using a jQuery mobile fixed footer.
I have tried to initialize this using both the pagecreate
and pageinit
event.
When I click on the links (being loaded with Ajax) in the footer and then come back to the page with the click handler the pagecreate
and pageinit
are being refired. This is attaching another click event, so when I click on the image 2 events are being fired.
I am wondering is there a jquery Mobile event that address this?? Did i miss something in the documentation?
I have addressed this problem by checking if the event exists before attaching it but it seems like jQuery mobile should have something to that handles this? I have done
var events = $('.ui-block-b img').data('events');
if (typeof events == 'undefined') { // attach handler}
Perhaps jQuery mobile already addressed this issue and I'm just missing something?
Upvotes: 2
Views: 1595
Reputation: 4019
You shouldn't load JS with a new page, as you know the issue you're having is that the JS is running everytime the page is created and each time it binds another click event.
The solution is to reference your elements with the native jQM pointer $.mobile.activePage which is available after the pageshow event fires. Or by putting a jQuery on listener at the root page div (not the document) in the pageinit event.
By using $('.ui-block-b img').click(function(event) {}
you are potentially attaching a bind event to elements in more than one page (since jQuery appends pages to the DOM), which is what you're doing.
<script type="text/javascript">
$("div:jqmData(role='page'):last").bind('pageinit', function(){
//your code here - $.mobile.activePage not declared, but you can setup
// "on" events here that handle elements ONLY on this page
//e.g. $(this).on('click', 'img.ui-block-b', function(){});
// this puts a live event listener that only listens for this page
});
$("div:jqmData(role='page'):last").bind('pageshow', function(){
//your code here - $.mobile.activePage works now
});
</script>
Now when you bind events you are ensuring you are only affecting the elements on the current page.
Organizing this is a bit of a pain so I have outlined a better solution I gave to another question here: Jquerymobile - $.mobile.changepage
Upvotes: 3