You are currently browsing the archives for the JavaScript category


AT&T Best Practices Guide for App Development

When considering the various best practices surrounding the design of Mobile Web Experiences and Architectures, such works as the W3C’s Mobile Web Application Best Practices guide, or the excellent Mobile Web Best Practices site, and of course, the seminal text, Mobile First, are likely to come to mind. The concepts and strategies presented in these works are a staple in the design of many modern Mobile Web Experiences and are without question an invaluable resource. In addition to these and other similarly related works, another new and valuable resource has been made available from a very important player in the Mobile Space indeed – an actual Wireless Carrier, AT&T.

Recently, I was contacted by a representative of the AT&T Developer Program informing me of the research conducted by the AT&T Research Labs and, the subsequent resources made available by AT&T as a result of their findings. Since I was unaware of this work, I was very interesting in learning more and, after reading the introductory statements, I was quite eager to apply AT&T’s recommendations as well; to quote specifically:

We quickly saw that a few, simple design approaches could significantly improve application responsiveness.

Having read through the material in it’s entirety (provided below) I must say I am rather impressed. The information provided has very real and practical implications on the design of Mobile Web Applications. Specifically, I found the clear and concise explanation of the underlying implementation of the Radio Resource Control (RRC) protocol to be particularly relevant and useful. RRC is by far one of the most important design factors to consider in terms of battery life and Application responsiveness and, as the research suggests, this may not have been common knowledge.

By far, the most interesting and notable aspect of the AT&T Research Lab’s work in this area is the fact that all of the information provided is applicable in the context of all Wireless Carriers, not just AT&T. That is, the recommendations given, such as those regarding the RRC State Machine, for example, are all based on carrier-independent standards and protocols implemented by all Wireless Carriers. As such, understanding the implementation specifics and recommendations provided is certain to prove valuable for all users of your Application, regardless of their Carrier.

If you haven’t all ready, I highly recommend reading and applying the principles provided by AT&T’s research to your current and future Mobile Web Application Designs.

AT&T Research Labs: Mobile Application Resources

Build Efficient Apps
Profiling Resource Usage for Mobile Applications: A Cross-layer Approach

External Templates in jQote2

The jQote2 API Reference provides plenty of useful examples which are sure to help users get up and running quickly. I found it a bit unclear, though, as to how templates could be loaded externally as, in the reference examples, templates are defined within the containing page. For the sake of simplicity this approach certainly makes sense in the context of examples. However, in practice, templates would ideally be loaded externally.

While jQote2 provides a perfect API for templating, it does not provide a method specifically for loading external templates; this is likely due to the fact that loading external templates could easily be accomplished natively in jQuery. However, since this is a rather common development use case, having such a facility available would be quite useful.

After reviewing the comments I came across a nice example from aefxx (the author of jQote2) which demonstrated a typical approach to loading external templates which was simular to what I had been implementing myself.

And so, I wrote a simple jQuery Plug-in which provides a tested, reusable solution to loading external templates. After having leveraged the Plugin on quite a few different projects, I decided to open source it as others may find it useful as well.

You can grab the source and view the example over on the jQote2 Template Loader Github page.

DHTMLX Touch 1.0 Released

Last week, shortly after I blogged about the release of jQuery Mobile 1.0, I received an email informing me of the release of another Mobile Web Framework: DHTMLX Touch 1.0.

Being that I was unfamiliar with DHTMLX Touch (as I have been using jQuery Mobile almost exclusively), I was quite interested to learn more; and, having tried the Examples and reviewed the Documentation, I was rather impressed by DHTMLX Touch.

And so, if you haven’t already, check it out.

Function Overwriting in JavaScript

Whether intentional, or simply a by-product of it’s design, Javascript, being a dynamic language, allows for a level of expressiveness which most any seasoned programmer would come to appreciate. Javascript naturally provides the ability to implement some rather intriguing and quite unique patterns; one of which is the ability to overwrite a function at runtime.

Function Overwriting

Function Overwriting (also known as “Self-Defining Functions” or “Lazy Defining Functions”) provides a pattern which, as stated above, allows for overwriting a function’s definition at runtime. This can be accomplished from outside of the function, but also from within the function’s implementation itself.

For example, on occasion a function may need to perform some initial piece of work, after which, all subsequent invocations would result in unnecessarily re-executing the initialization code. Typically, this issue is addressed by storing initialization flags or refactoring the initialization code to another function. While such a design solves this problem, it does result in unnecessary code which will need to be maintained. In JavaScript, perhaps a different approach is in order: we can simply redefine the function after the initialization work has been completed.

A possible candidate use-case for Function Overwriting is Feature Detection as, detecting for specific feature support in the Browser typically only needs to be tested once, at which point subsequent tests are unnecessary.

Below is a basic example of implementing Function Overwritting in the context of an abstraction of the HTML5 Geolocation API.

// Initial "getLocation" implementation. Since we only need to test
// for Geolocation support once, we perform the initial test and then
// overwrite the "getLocation" implementation based on the results of
// the test.
var getLocation = function ( success, fail, options )
{
    var geolocation = navigator.geolocation;

    if ( geolocation )
    {
        var _options = {
            enableHighAccuracy : true,
            timeout            : 60000,
            maximumAge         : 0
        };
        // Geolocation is supported, so we overwrite the implementation
        // to simply invoke "geolocation.getCurrentPosition" as there
        // is no need to perform the test again.
        getLocation = function (success, fail, options)
        {
            geolocation.getCurrentPosition ( success,
                    fail,
                    options || _options);
        }
        getLocation( success, fail, options );
    }
    else
    {
        // Geolocation is not supported, so we overwrite the
        // implementation to simply return false (a real
        // implementation might provide a polyfill here…).
        getLocation = function ()
        {
            return false;
        }
    }      
};

Considerations

Since functions are objects in Javascript, it is important to keep in mind that if you add a property or method to a function (either statically or via the function’s prototype), and then overwrite the function, you will have effectively removed those properties or methods as well. Also, if the function is referenced by another variable, or by a method of another object, the initially defined implementation will be preserved and the overwriting process will not occur. As such, be mindful when implementing this pattern. As a general rule of thumb, I typically only implement Function Overwriting when the function being redefined is in a private scope.

Concluding Thoughts

As you can see, Function Overwriting provides a convenient facility for optimizing code execution at runtime. There are many use-cases for dynamically overwriting functions and, where appropriate, they can certainly provide value in terms of performance and code maintainability.

Below you can find an example which demonstrates two basic Function Overwriting implementations. Simply load the page and add some breakpoints in Firebug to test the execution paths; both before and after overwriting each function occurs, or you can simply view the source.
Example

Refreshing listviews in jQuery Mobile

When dynamically creating or updating a list in jQuery Mobile; either via AJAX or by other means, one must take care to explicitly invoke the target listview widget to “refresh” in order to instruct the framework to apply the augmented markup and styles to the corresponding elements of the underlying list.

For example, consider the following simplified example which creates an li element for each item in an Array:

var list = "",
    items = [{name: "Item A", url: "/#item-a"},
             {name: "Item B", url: "/#item-b"},
             {name: "Item C", url: "/#item-c"}];

$.each( items, function( i, item ) {
    list += ‘<li><a href="’ + item.url + ‘">’ + item.name +‘</a></li>’;
});
$("ul:jqmData(role=’listview’)").append( list );

While this will create the list items and add them to the target listview ul element, JQM will not auto enhance the newly added items unless instructed to do so. I imagine this is due to a necessary design decision as, constantly monitoring the DOM for changes would certainly incur a performance hit.

In order to correct this, we just need to invoke .listview("refresh"); after appending the new elements to the list. This will notify JQM to apply the expected enhancements. And so, the following example will result in the expected list enhancements being applied:

var list = "",
    items = [{name: "Item A", url: "/#item-a"},
             {name: "Item B", url: "/#item-b"},
             {name: "Item C", url: "/#item-c"}];

$.each( items, function( i, item ) {
    list += ‘<li><a href="’ + item.url + ‘">’ + item.name +‘</a></li>’;
});
$("ul:jqmData(role=’listview’)").append( list ).listview("refresh");

You can try an example which demonstrates both of the above implementations here.

jQuery Mobile 1.0 Released

, the jQuery Mobile Team announced the official release of jQuery Mobile 1.0.

Having worked with jQuery Mobile since Alpha 1, in the time since, the framework has certainly evolved into a mature, premier platform on which Mobile Web Applications can be built.

On a personal note, as I am currently in the process of working towards the release of a multi form-factor Mobile Web Application built on jQuery Mobile, the 1.0 release couldn’t have come at a better time.

Be sure to check out the updated API Docs, especially the new Data Attributes section.

jQuery Mobile 1.0 represents a significant milestone in the Mobile Web Space. I am certainly excited to see what is on the roadmap next.

CSS3 Combinators

In my previous article on CSS3 Selectors, I discussed the two Attribute Selector classifications; Attribute Presence and Value Selectors, and, Attribute Substring Matching Selectors.

In addition to the new Attribute Selectors, the CSS3 Selectors Module defines a new Combinator called the General sibling combinator, which is described below, succeeding a review of each CSS3 Combinator.

Combinators

Combinators provide a means for describing relationships between elements in order to “combine” them to form specific rules based on a simple syntax. There are four Combinators in CSS3, below is description and example of each:

Descendant combinator
The most familiar of all Combinators, the Descendant combinator allows for selecting any element f which is a descendant (child, grandchild, great-grandchild and so on) of an element e. The combinator syntax for a Descendant combinator is a single “white-space” character.

/* Matches all <h1> elements which are descendants of an <article> element */
article h1{
    /* declarations */
}

8.1. Descendant combinator

Child combinators
Child combinators allow for selecting any element f which is a direct child of an element e. The combinator syntax for a Child combinator is a single “greater-than” (>) sign.

/* Matches each <section> element that is a direct child of an <article> element */
article > section {
    /* declarations */
}

8.2. Child combinator

Adjacent sibling combinator
The Adjacent sibling combinator is a Sibling combinator which allows for selecting an element f which is adjacent to an element e; that is, element f immediately follows element e in the document tree. The combinator syntax for an Adjacent sibling combinator is a single “plus” (+) sign.

/* Matches all <em> elements which are the next sibling of a <strong> element */
strong + em {
    /* declarations */
}

8.3.1. Adjacent sibling combinator

General sibling combinator
New in CSS3, the General sibling combinator is similar to the Adjacent sibling combinator in that it matches an element f which follows an element e in the document tree; however, whereas in the Adjacent sibling combinator element f must immediately follow element e, the General sibling combinator allows for selecting an element f which is preceded by an element e, but not necessarily immediately preceded by an element e. The combinator syntax for a General sibling combinator is a single “tilde” (~) sign.

/* Matches all <time> elements which are preceded by a <del> element */
del ~ time {
    /* declarations */
}

8.3.2. General sibling combinator

The following link provides a (rather crude in terms of design) example of each Combinator described above:
View Example

CSS3 Attribute Selectors

The power of CSS Selectors can not be understated; for, without them, there would be no simple means by which developers could target specific elements for styling in a manner abstracted from, or external to, the actual markup to which the styles will bind.

In addition to some of the more common Simple Selectors, such as Type Selectors, Class Selectors and Id Selectors, we have have Attribute Selectors, which, as the name implies, allow us to match elements based on their attributes.

Attribute Presence and Value Selectors

CSS2 introduced four Attribute Selectors; referred to as Attribute Presence and Value Selectors, which allow for course grained matching of specific elements based on their attributes and / or attribute values. These include the following:

e[attr]
Where e is an element and [attr] is an attribute of element e. For example, p[title] would match all p tags with a title, regardless of the value of the title.

/* Matches all <p> tags with a title and changes their background color to red with white text */
p[title]{
    background-color: red;
    color: white;
}
e[attr=val]
Where e is an element and [attr=val] represent an attribute of element e which contains the exact value of val. For example, p[title="Example 1"] would match all p tags with a title which equals “Example 1″ exactly.

/* Matches all <p> tags with a title equal to "Example 1" and changes their background color to green and text color to white */
p[title="Example 1"]{
    background-color: green;
    color: white;
}
e[attr~=val]
Where e is an element and [attr~=val] is an attribute of element e which has a value containing a whitespace-separated list of words, one of which equals val exactly. For example, p[title~="Example-1a"] would match all p tags with a title containing the word “Example-1a” in a list of whitespace delimited words.

/* Matches all <p> tags with a title containing the exact word to "Example-1a" and changes their background color to black and text color to red */
p[title~="Example-1a"]{
    background-color: black;
    color: red;
}
e[attr|=val]
Where e is an element and [attr|=val] is an attribute of element e that has a value of val exactly, or begins with val immediately followed by a hyphen “-”. For example, p[title!="Example"] would match all p tags with a title containing the word “Example-”, followed by any other value, such as “Example-1″, “Example-A”, etc..

/* Matches all <p> tags with a title containing the word to "Example-" and changes their background color to blue and text color to white */
p[title|="Example"]{
    background-color: blue;
    color: white;
}

View Example

Substring Matching Attribute Selectors

In addition to the above Attribute Presence and Value Selectors, CSS3 expands on this by defining three additional Attribute Selectors; referred to as Substring Matching Attribute Selectors. These additions allow for fine grained matching of specific elements based on their attribute values.

In simplest terms, the new Attribute Selectors in CSS3 can be used to match an element with a given attribute whose value begins, ends or contains a certain value. The following is a basic description and example of each new Attribute Selector:

e[attr^=val]
Where e is an element and [attr^=val] is an attribute of element e which contains a value that begins with val.

/* Matches all linked resources sent over https */
a[href^="https"]{
    color: red;
}
e[attr$=val]
Where e is an element and [attr$=val] represent an attribute of element e which contains a value that ends with val.

/* Matches all anchor tags to .html documents */
a[href$=".html"]{
    color: green;
}
e[attr*=val]
Where e is an element and [attr*=val] is an attribute of element e which has a value that contains val.

/* Matches all anchor tags which contain a query string */
a[href*="?"]{
    color: blue;
}

View Example

To summarize, there are a total of seven Attribute Selectors in CSS3, three of which are new. Whether used for general matches, such as global Attributes; e.g. *[hreflang|=en] or more specific matches, such as chaining; e.g, a[href^="https"][target="_blank"], Attribute Selectors provide a powerful mechanism for selecting both general and specific content within a page.

Circumventing Conditional Comparisons

Often during the course of my day I come across code which evaluates the same conditional comparisons in multiple contexts. Understandably, this is rather typical of most software systems, and while it may only introduce a negligible amount of technical dept (in the form of redundancy) for smaller systems, that dept can grow considerably in more complex, large scale applications. From a design perspective, this issue is applicable to nearly every language.

For example, consider a simple Compass class which defines just one public property, “direction” and, four constants representing each cardinal direction: North, East, South and West, respectively. In JavaScript, this could be defined simply as follows:

var Compass = function(direction){
    this.direction = direction;
}
Compass.NORTH = "North";
Compass.EAST  = "East";
Compass.SOUTH = "South";
Compass.WEST  = "West";

Technically, there is nothing problematic with the above class signature; the defined constants certainly provide a much better design than conditional comparisons against literal strings throughout implementation code. That being said, this design does lead to redundancy as every instance of Compass which needs to evaluate the state of direction requires conditional comparisons.

For example, to test for Compass.North, typically, client code must be implemented as follows:

if (compass.direction === Compass.NORTH) {
    //…
}

Likewise, simular comparisons would need to be implemented for each cardinal direction. And, while this may seem trivial for a class as simple as the Compass example, it does become a maintenance issue for more complex implementations.

With this in mind, we can simplify client code by defining each state as a specific method of Compass. In doing so, we afford our code the benefit of exercising (unit testing) Compass exclusively. This alone improves maintainability while also simplifying client code which depends on Compass. As such, Compass could be refactored to:

var Compass = function(direction){
    this.direction = direction;
}
Compass.prototype = {
    isNorth: function() {
        return this.direction === Compass.NORTH;
    },
    isWest: function() {
        return this.direction === Compass.WEST;
    },
    isSouth: function() {
        return this.direction === Compass.SOUTH;
    },
    isEast: function() {
        return this.direction === Compass.EAST;
    }
}

Based on the above implementation of Compass, the previous conditional comparison can be refactored as follows:

if (compass.isNorth()) {
    //…
}

Comparator API

To simplify implementing conditional comparisons, I have provided a simple Comparator API that defines a single static method: Comparator.each, which allows for augmenting existing objects with comparison methods. Comparator.each can be invoked with three arguments as follows:

type
The Class to which the comparison methods are to be added.
property
The property against which the comparisons are to be made. If the property has not been defined it, too, will be added.
values
An Array of constants where each value will be used to create a new comparison method (prefixed with “is”). If the constants specified are Strings, typically an Array containing each constant should suffice. For example, passing [Foo.BAR] where BAR equals “Bar” would result in an isBar() method being created. To specify custom comparison method names, an Object of name/value pairs can be used where each name defines the name of the method added and the value is the constant evaluated by the method. This is useful for constants which are not strings. For example, {isIOS421: DeviceVersion.IOS_4_2_1} where IOS_4_2_1 equals 4.2.1 would result in an isIOS421() method being created.

Taking the Compass example, the previous comparison methods could be augmented without the need to explicitly define them via Comparator.each:

var Compass = function(){
    this.direction = direction;
}
Compass.NORTH = "North";
Compass.EAST  = "East";
Compass.SOUTH = "South";
Compass.WEST  = "West";
Comparator.each( Compass, "direction", [Compass.NORTH,
                                        Compass.WEST,
                                        Compass.SOUTH,
                                        Compass.EAST] );

The above results in the comparison methods isNorth, isEast, isSouth and isWest being added to the Compass type.

Comparator: source | min | test (run)

Interconnectivity in JavaScript with Peerbind

The ability to facilitate interconnectivity between multiple clients has always presented some rather interesting possibilities for both simple and complex Web Applications alike. More often than not, such interconnected applications would require complex server-side configurations (often proprietary in nature) in addition to numerous infrastructure considerations.

Peerbind, a new JavaScript API, remedies many of these complications by providing a very simple client-side API built on jQuery.

Peerbind is quite unique in that it provides an event binding API (on top of jQuery) that is shared amongst all connected clients of the same interest. Essentially this allows for binding something as common as a “click” event (or any event for that matter, including custom events) such that each active instance of the same application across the web will be notified of the event. As one might imagine, this allows for some rather compelling possibilities.

To demonstrate just how quickly and easily interconnectivity can be plugged into a web application using Peerbind (and the Peerbind public server), below is a simple example which displays a new item each time a new “peer” views the example page since loaded (hint: try opening a few instances, either in tabs or separate browsers).

<!doctype html>
<html>
    <head>
     <meta charset="utf-8" />
     <title>Simple Peerbind Example</title>
     <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
     <script src="http://js.peerbind.com/jQuery.peerbind.js"></script>
        <script>
            var Peers = (function()
            {
                var added = function(e)
                {
                    var timestamp = new Date(e.timeStamp);
                    var visitor   = e.srcPeer ? "New Visitor" : "You";
                    var item = "<li>" + visitor + " arrived on " +
                                        timestamp + "</li>";
                    $("#visitors").preppend( item );
                }
                var init = function()
                {
                    var body = $(document.body);
                    body.peerbind( "peer", added );
                    body.peertrigger( "peer" );
                }
                return {
                    init: init
                }
            }());
            $(document).ready( Peers.init );
        </script>
    </head>
    <body>
        <ul id="visitors"></ul>
    </body>
</html>

Example (run)

Simple enough!

Of course, for most applications there are obvious security concerns which would need to be addressed as well as issues of scale and availability to take into consideration. That being said, if you haven’t checked out Peerbind yet and would like to quickly and easily add interconnectivity to your application or leverage it’s simplicity to prototype such features, it is certainly worth taking for a test drive.