I am working on a single page JQuery Mobile site. JQuery initialization is initially set to false while JSON data is loaded and the DOM is manipulated client side. After the content is loaded and DOM manipulated, JQuery Mobile is initialized.
Once initialized, I am planning to use Ben Alman’s replaceText plugin to drop JSON into some placeholders that are within the outputted HTML, so a placeholder like “XXFIRST_NAMEXX” becomes “John Smith”.
I haven’t gotten to the replacement part b/c I am unable to access the JSON data from within JQuery Mobile’s pageshow() event, even though that the last event to fire in the sequence of events loading the page.
Below is a simplified and commented version of my code.
I am using JQuery 1.7.1 and JQuery Mobile 1.1.0
What am I missing here?
Thanks!
// jQuery Mobile initialization
$(document).bind("mobileinit", function () {
//prevent JQM from initializing until after content has been loaded in .getJSON callback;
$.mobile.autoInitializePage = false;
});
$( document ).bind( "pageshow", function( event, data ){
console.log('pageshow fires'); //fires 4th
//DROP-INS
//need to replace text within manipulated and initialized html
var resplaceScope, strDisplayName, strSchoolName, strOfferTitle;
replaceScope = $('body *');
//collect variables from json data
strOfferTitle = data.content.offer_vars.offer_title; //ERROR Uncaught TypeError: Cannot read property 'offer_vars' of undefined
replaceScope.replaceText( /XXOFFER_TITLEXX/gi, strOfferTitle );
});
$(document).ready(function(){
console.log('document.ready fires'); //fires 1st
$.getJSON('io_content.json', function(data) {
console.log('getJSON fires'); //fires 2st
getContent(data);
// ... once code is manipulated by getContent, Jquery is ready to initialize
$.mobile.initializePage();
});
function getContent(data){
console.log('getContent fires'); //fires 3rd
// ... code to manipulate content client side before jquery mobile initializes
}
});
I’m not entirely sure what’s going on, but is it possible that you’re expecting the “data” parameter passed into the “pageshow” callback to be the same as the “data” variable in the “getJSON” callback? They are different objects that just happened to both be named “data”. The one from “pageShow” just has a “prevPage” property that contains a reference to the DOM element that represents the page that was just navigated away from. The one in the getJSON callback has the actual data you got from the data source; once the callback finishes executing, it’s gone.
If it’s not possible to do all of this initialization in the JSON callback, then you might try using jQuery’s data() function to store the bits of the JSON that you need on some DOM element in the page. http://api.jquery.com/jQuery.data/
Does that help?