1

I am playing with my first PhoneGap/Android app, and am having trouble triggering $.mobile.changePage() from a PhoneGap/Cordova Event.

I've updated the code, whereas before it would trigger once. Now it does not trigger at all, but is closer to how it probably should be done.

Here is my code:

    $(document).on('pageinit', function() {
        document.addEventListener("searchbutton", onSearchKeyDown, false); //never fires
        document.addEventListener("menubutton", onMenuKeyDown, false); //never fires
        alert("triggered"); //does fire
    });

    // search button press
    function onSearchKeyDown() {
        //change to search page
        alert("search");
        $.mobile.changePage("#page4", {transition: "pop"});
    }

    //menu button press
    function onMenuKeyDown() {
        //change to start page
        alert("menu");
        $.mobile.changePage("#page1", {transition: "pop"});
    }
Tank
  • 1,006
  • 7
  • 17
  • 1
    check this http://stackoverflow.com/questions/9631933/override-android-backbutton-behavior-only-works-on-the-first-page-with-phonegap for the answer – dhaval Mar 20 '12 at 05:39
  • Thanks, I found the answer there. – Tank Mar 20 '12 at 16:15

2 Answers2

2

Use pageInit(), not $(document).ready().

See the documentation here:

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.

Ryan
  • 26,884
  • 9
  • 56
  • 83
  • I've read up on pageinit, and updated my code to use it.. but now it has 0 functionality. – Tank Mar 19 '12 at 19:36
  • Have you tried adding a `` to the page and then initializing the PhoneGap event handlers there? It's been a while, but PhoneGap and jQuery Mobile have different ways of doing things. It's possible that when jQuery Mobile is ready (paeginit), PhoneGap is not ready yet. Or vice versa. – Ryan Mar 19 '12 at 21:34
  • Yes, that was the first method I tried, by example of phonegap's website. It produced the same results as $(document).ready(), the buttons worked once. – Tank Mar 20 '12 at 13:09
1

Here is the solution if anyone else has this problem. via https://stackoverflow.com/a/9739986/799876

A few lines up from the bottom of cordova.js, there is the line

channel.onNativeReady.subscribe(_self.boot);

Change it to

channel.onNativeReady.subscribeOnce(_self.boot);

For me, this fixed the menubutton and searchbutton events with phonegap & jQuery Mobile.

Community
  • 1
  • 1
Tank
  • 1,006
  • 7
  • 17