Archive | August, 2011

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");
      pageController.processAction($(this));
});
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: http://api.jquery.com/live/

Reusability

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

Readability

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