Single Page AIR Applications with jQuery

Quite a few people have asked how to create AIR applications that utilize the "one page" approach. There are many benefits to this method, most importantly variable scope. In AIR when you switch from one page to another you lose the data you've already got loaded onto the current page. With a single page approach, you're making external page calls via AJAX to load in parts of pages, keeping all current data available to the current page and new pages as well. Using jQuery it couldn't be simpler. Let's see how it works. But first take a minute to download the Single Page AIR Applications source for your reference.

Create a new AIR project and some additional pages. We'll be loading the extra pages in using jQuery's $.load() method. Before we move on let's take a quick look at how the $.load() method works.

The load method is generally attached to a container, in the example above, that's one with an id of containerToLoadInto. The load method will look for a page called test.html. Now here's the cool part...jQuery will load in that page, and if the optional target search param, #sourceContainer, is found it will extract that container (and it's contents) and place them inside the containerToLoadInto container. Finally, there's an optional callback function available for your use.

To honor the pending arrival of my third child the project has a pregnancy theme, with information taken from Wikiepedia's article on pregnancy. In this example I have a list of links I'm using as navigation. When the link is clicked I'm extracting the href from the anchor tag and passing it to the load method.

This couldn't be simpler, but it can be more robust as well. One thing this method doesn't offer is bookmarking. Now that's probably not as important in desktop applications, but it could be useful. There are ways of approaching this in code, but if you're looking for more robust routing support, then I'd recommend looking into Sammy. It bills itself as a "RESTful Evented JavaScript" and built on top of jQuery. If you're already familiar with languages like Ruby that offer routing based on the URL then Sammy is the JS framework for you.