3

I'm transferring a normal site to jQuery mobile. I've got some of event bindings, as well as other page specific adjustments:

$('.roulette-img').css({
});

$('.shuffle-img').each(function(){
});

$('.button').bind('mousedown', function(){
});

$('.spin-btn').bind('mousedown', function(){
    $(document).bind('mouseup', function(){
    });
})

$(window).resize(function(){
});

Right now certain pages don't work as they should (by not firing these events). I understand this is because of jQuery's ajax navigation, that the script only loads once when the first page is loaded and as a result all subsequent content loaded in via AJAX doesn't get binded to events.

Which way is the best to get around it?

Gajotres
  • 57,309
  • 16
  • 102
  • 130
styke
  • 2,116
  • 2
  • 23
  • 51

2 Answers2

1

First don't use bind, it is deprecated and removed from jQuery versions 1.9 +. Use on instead. Here's an example:

$('#buttonID').on('click', function(){       

});

Also if you want to execute something inside a certain page you need to do it inside a jQuery Mobile page event, like this:

$(document).on('pagebeforeshow', '#index', function(){       

});

I made you a working example: http://jsfiddle.net/Gajotres/8hKe2/

Here you can see what it looks to use page events to execute a code for specific pages.

everything you want to know can be found in this answer/article: jQuery Mobile: document ready vs page events

Community
  • 1
  • 1
Gajotres
  • 57,309
  • 16
  • 102
  • 130
  • 1
    Thank you, absolutely fantastic article. Extremely in depth and exactly what I needed. Take care. – styke Apr 05 '13 at 09:48
  • @Gajotres, IIRC we already debated this before, but don't you think binding to `pagebeforeshow` instead of `pageinit` can result in the `mousedown` handlers being bound multiple times if a page is hidden then shown again? – Frédéric Hamidi Apr 05 '13 at 09:51
  • This is just an example. No point in explaining everything when I have other article describing this in great detail: http://stackoverflow.com/a/14469041/1848600, same article that's posted in my answer. – Gajotres Apr 05 '13 at 09:52
  • Also, `bind()` is neither deprecated nor removed. `on()` arguably supersedes it, but `bind()` and `unbind()` can still be used. Were you thinking about `live()` and `die()`? – Frédéric Hamidi Apr 05 '13 at 09:53
0

If you want your handlers to be bound to new pages as they're loaded, you can use the pageinit event and restrict your selectors to the page that is currently initialized:

$(document).on("pageinit", function(e) {
    $(".button", e.target).on("mousedown", function() {
        // ...
    });

    $(".spin-btn", e.target).on("mousedown", function() {
        // ...
    });
});
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479