Adding a controller to JQueryMobile

1 Aug

JQuery Mobile highlights the power of HTML5 data attributes. An example div element with such an attribute could be:

<div data-role="header">

This new feature introduced in HTML5 – but backwards compatible with previous versions – is able to provide us with the flexibility to say what we mean rather than impreatively tell the code to do something. Im talking about declarative vs imperative programming.

Why Controllers in javascript?

Controllers are a part of the MVC pattern and are quite common in many areas of programming, however in my experience not so common in javascript development. This is possibly due to the requirement of javascript growing more and more as time goes on, and possibly due to the small scale in which it is usually used. Mobile development with phone gap tends to challenge this perspective of javascript by enabling large javascript applications to be developed in the mainstream.

Proposed approach

The Html

<a data-action="postForm">

The JQuery

$('a[data-action*=""]').live('click', function () {
      Log("Click -> Action");
var pageController = new PageController();

function PageController() {
    this.processAction = function (itemWithAction) {

        var action = itemWithAction.attr('data-action');

        //Log("action = " + action);

        //Do something with the action here!!!

Performance benefits

Subscribing one click event to all necessary elements of the DOM for an application will be quite the performance hit. Instead this solution is subscribing to the root element of the DOM once. For more information see:


The actions are able to be reused across multiple pages. They are fully separated from the page, with a reference to the triggering element.


Html elements that use data attributes to call actions make tracing event-action mappings much easier

2 Responses to “Adding a controller to JQueryMobile”

  1. petermaury August 6, 2011 at 2:51 am #

    i’m using as a mvc url router. seems promising

  2. rhwilburn August 7, 2011 at 4:53 am #

    Thanks for the link, its very interesting. I hadn’t thought about making actions page states accessible by URL’s.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: