Search code examples
jqueryjquery-mobileibm-mobilefirstjquery-events

Where to put script tag inside jQuery mobile single page template


I have two page written in the single page template way.

Login.html has <script src="login.js" /> in his <head></head> and this is like:

$(document).on("pageinit", "#loginPage", function(){
   $("#loginBtn").on("tap", function(){
      // if you are already authenticate or login success...
      $.mobile.changePage("Main.html");
   });
});

Main.html has is <script src="main.js" /> in his <div data-role="page" id="main"></div> and this is like:

$(document).on("pageinit", "#main", function(){
//if not authenticated go to login
   $.mobile.changePage("Login.html");

    callJsonService();

$("#btnLogout").on("tap", function(){
            //do logout operatio and go back to login
    $.mobile.changePage("Login.html");
}).on("vmousedown", function(){
    $(this).addClass("tapped");
}).on("vmouseup", function(){
    $(this).removeClass("tapped");
});

If you navigate back and forward these 2 pages, every time you visited the page, the event bound with on() are fired two times, then three times, then four times etc. etc.

Why is this happening? It is due to the 'pageinit' event? or it is not correct to put the main.js inside the div with data-role=page?


Solution

  • Don't load JS within your <div data-role="page"/> it will fire multiple times, I like to bind an on listener to the document root in a js file that I include on each page

    $(document).on('pageinit pageshow', 'div:jqmData(role="page"),   
    div:jqmData(role="dialog")', function(event){
    

    Now place some sort of data variable or class on your <div data-role="page" data-pageid="foo"/> to distinguish between your different pages, now you have two variables to branch your code on

    1. event.type = pageinit/pageshow: the first fires once only for each page, latter will fire on first load and re-fire if you press back and navigate back to the page

    2. $(this).data('pageid') = whatever you want, in this case when page foo fires either event you can handle appropriately, no surprises

    See my older answer: https://stackoverflow.com/a/10542821/737023 for more detail