Tuesday, September 27, 2011

document.ready with jQuery Mobile

One of the first hurdles I had with creating sites with jQuery Mobile was figuring out how to run my code when a page loads.  Since navigating to a new page no longer requires a postback, the standard $(document).ready approach isn't going to cut it.  I've come up with a solution that I think helps you modularize and isolate your code to prevent having one large unmaintainable lump of a javascript file.

Creating a Namespace

Now when I work on javascript heavy applications, I take care to modularize my javascript but I don't necessarily follow the pattern exactly.  I start out by creating a namespace object, and I usually place this in a file called core.js.

So, what we're doing here is creating a blank object (MYAPP) to "scope" our application objects.  We extend that object with some new objects to hold our pages and maybe even some options.  We would also maybe put some other stuff in here, but for this example we'll keep it mostly clean.

The Page Event Mapper

Now it's time to do some plumbing work to hook the new page objects we are going to create up to the jQuery Mobile navigation framework.  We want to pass the page events from jQuery Mobile to a page class that will handle the events.

Every page in jQuery mobile is wrapped in a div with a data-role attribute set to "page", so what we're doing here is handling the jQuery Mobile page events and passing them to our corresponding page.

A Page Class Example

Speaking of pages, let's take a look at what an example page looks like in my code.

As you can see, I've kept the code pretty simple.  This class will now be able to respond to init events (which get fired before the page is modified by jQuery Mobile) and the show event which gets fired every time the page is navigated to (even when it's cached and navigated back to).

But Don't Take My Word For It

If you want to give a try for yourself, head on over to the jsFiddle I set up with this example code already set up.


No comments:

Post a Comment