Skip to content

Instantly share code, notes, and snippets.

@jgable
Created September 27, 2011 22:07
Show Gist options
  • Save jgable/1246402 to your computer and use it in GitHub Desktop.
Save jgable/1246402 to your computer and use it in GitHub Desktop.
document.ready alternatives for jQuery Mobile - core.js
// Create our namespace object, use one that already exists if it's available, fall back to new object "{}".
var MYAPP = MYAPP || {};
(function($, ns) {
// .. This is a closure, so we don't muddy up our global namespace.
// .. $ = jQuery, ns = MYAPP (For those playing along at home)
// Extend our namespace with some stuff we're going to add later.
ns = $.extend(ns, {
options: {}, // MYAPP.options
pages: {} // MYAPP.pages
});
}(jQuery, MYAPP));
// Set up our "home" page class and let it respond to events.
(function($, ns) {
// See http://jquerymobile.com/test/docs/api/events.html for more info about events
function homePage() {
};
homePage.prototype.init = function($page, pageDom) {
alert("In the init event boiiii!");
};
homePage.prototype.show = function($page, pageDom) {
alert("In the shown event, yeaaahhhh booiiiii!");
};
// "Export" the page to our pages namespace.
ns.pages = ns.pages || {}; // Some safety fall backs in case the pages namespace isn't created yet.
ns.pages.home = new homePage();
}(jQuery, MYAPP));
// Set up the page handler that will fire events in our page classes.
(function($, ns) {
// Set up a map to our pages namespace; MYAPP.pages
var pageNS = ns.pages,
pageKeyAttr = "data-pages-key";
// Map page events to our pages
// See http://jquerymobile.com/test/docs/api/events.html for more info about page events
$("div[data-role*='page']").live('pagebeforecreate pagecreate pageinit pagebeforeshow pageshow pagebeforehide pagehide', function (event, ui) {
// pass the page (this) and the event name ("pageinit" = "init" with slice(4))
handlePageEvent(this, event.type.slice(4));
});
// page event handler
function handlePageEvent(page, evtName) {
// Get the id of our page from the page attribute, fall back to id if not found.
var $this = $(page),
thisId = $this.attr(pageKeyAttr) || $this.attr("id");
if (!thisId) {
// Back out if no id defined...
return;
}
// Remove any sketchy characters...
thisId = thisId.replace(/\.html$/gi, "");
// Check for page in the namespace and fire off the shown function.
if (pageNS[thisId] && (typeof pageNS[thisId][evtName] === 'function')) {
log('firing event on page', evtName);
pageNS[thisId][evtName]($this, page);
}
};
}(jQuery, MYAPP));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment