Mad Echet
Mad Echet

Reputation: 3881

Page overwritten in jQuery Mobile

I am trying to navigate around pages in jQuery Mobile and I am having trouble with dynamically created page and ajax loaded ones.

I have a page (page_2) from which I dynamically create a page (page_3) by using page3.appendTo($.mobile.pageContainer); and then $.mobile.changePage(page3);. It works fine and I can go back to page_2 by doing $.mobile.changePage($("#page_2"));. So far so good.

The problem is when I land in page_2 from another page (eg page_1). It this case, for some reason, page_2 disappears from $.mobile.pageContainer when I create page_3 (whereas page_1 remains). It prevents me from going back from the newly created page to page_2 where it technically belongs.

Any idea why? Is there any way I can prevent page_2 from being removed?

You can try it out there: page_1 and page_2

In short:
page_1 -> page_2 works
page_1 -> page_2 -> page_3 works
page_1 -> page_2 -> page_3 -> page_2 fails
page_2 -> page_3 -> page_2 -> page_3 works (however many loops you like)

Thanks a lot for your help!

Upvotes: 2

Views: 695

Answers (2)

Jasper
Jasper

Reputation: 76003

You can set the data-dom-cache attribute to true on the <div data-role="page" id="page_2"> element (the second page) so it isn't removed once it's navigated away from:

<div data-dom-cache="true" data-role="page" id="page_2">
    ...
</div>

Docs: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/data-attributes.html

jQuery Mobile's default behavior is to remove any pseudo-page from the DOM that was brought in by AJAX after the user navigates away from it. So when you link to remote documents, use absolute links that point to the URL of the document, not the ID of it's <div data-role="page"> element.

Your dynamically created page three uses this to navigate back to the second page:

$.mobile.changePage($("#page_2"));

It could change to:

$.mobile.changePage('/page_2.html');

If you link to pages like this, they will by default be removed from the DOM after they are navigated away from, the idea is that you are less likely to crash a mobile device's browser if there are minimal pages in the DOM. There is also the chance that the page will just be pulled in from cache so no HTTP request is made in that case.

Upvotes: 1

bmurmistro
bmurmistro

Reputation: 1080

I suggest using the jqm events for this:

$("#page3link").click(function (e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    createPage3();
    return false;
});

you'll need to do the same for the go back to button 2 link or you could just simply put and h ref="#page2"

Upvotes: 1

Related Questions