jQuery Mobile - pass data between pages
by Omar X
HTML
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<div data-role="page" id="p1">
<div data-role="content"> <a href="#" data-role="button" class="data" id="fruits">Fruits?</a>
<a href="#" data-role="button" class="data" id="vegetables">Vegetables?</a>
</div>
</div>
<div data-role="page" id="p2" data-add-back-btn="true">
<div data-role="header">
<h1>Header</h1>
</div>
<div data-role="content">
<p>Page Two</p>
</div>
</div>
JavaScript
/* For Demo */
/* add elements based on retrieved data */
function showStuff(page, data) {
var demo = {
"fruits": ["Orange", "Apple"],
"vegetables": ["Tomato", "Carrot"]
};
var list = $("<ul/>", {
"data-role": "listview",
"data-inset": true,
"data-theme": "b"
});
var items = '';
$.each(demo[data], function (i, v) {
items = $("<li>" + v + "</li>");
list.append(items);
});
$("ul", page).remove();
list.appendTo(page, "[data-role=content]");
$("ul", page).listview();
}
/* Pass data with changePage */
$(document).on("pageinit", "#p1", function () {
$(".data").on("click", function () {
$.mobile.changePage("#p2", {
stuff: this.id,
transition: "flip"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "p2") {
var stuff = data.options.stuff;
showStuff("#p2", stuff);
}
});