You are currently browsing the HTML5 archives.

HTML5 Document Outliner

Recently, while preparing a training session on HTML5 Semantic and Structural Elements, I was rather intent on conveying the importance of an application’s overall markup and structure, while also expressing the importance of not being overly concerned with the absolute technical “correctness” of each and every element used.

With this in mind, providing a general overview of HTML5 sectioning content, and HTML5 Document Outlines, seemed appropriate points to emphasize.

Before doing so, I was looking to utilize a simple utility to provide a means of visualizing an HTML5 Document Outline, and the very useful Chrome Extension, HTML5 Outliner, proved to be an ideal tool for the task.

In particular, the HTML5 Outliner is quite helpful in validating the overall structure of single page web applications, whereby the constructed page is based on multiple disparate client-side templates being rendered at runtime; in which case it can be rather useful to have a holistic view of an application’s structure.

And so, if you are building modern client-side web applications, and using Chrome, if you haven’t done so already, I certainly recommend installing the HTML5 Document Outline for quickly viewing an application’s overall structure.

Managing Client-side Templates with RequireJS

When developing single page web applications, patterns of structure, organization and reuse become ever more important. This especially holds true when there is a need to maintain mulitiple web applications, each of which targeting a specific form factor, while also sharing many of the same underlying core APIs.

In the context of client-side templating, such patterns begin to emerge, quite naturally so, when leveraging RequireJS modules and the RequireJS text plugin.

Template Modules

One specific pattern I have found myself implementing is that of a single Templates Module which provides a centralized location from which all compiled templates within an application can be referenced. A rather simple pattern, Template Modules are only concerned with loading, compiling and providing a public API to access compiled templates; that is, a Templates Module simply requires all external templates, and provides named methods for retrieving the compiled template functions of each.

A basic implementation of a Templates module is as follows (while Handlebars may be used in this example, any template engine would suffice):

The main benefit of implementing a Templates Module is reuse, as different modules can use the same templates without a need for redundantly requiring and compiling the templates themselves. Additionally, Template Modules provide a convenient means of abstracting away the underlying template engine from client code, thus reducing the amount of refactoring needed should the template engine itself ever need to change.

When using the RequireJS Optimizer, each external template will be included in the optomized build and loaded synchronously, and so there is no additional overhead in terms of HTTP requests when requiring each template in a single location.

You can check out a basic example implementation of a Templates Module (in the context of Backbone) here.

JavaScript Comma Delimiter Pattern

Perhaps the most common syntactic error I find myself correcting in JavaScript is that of a simple missing comma separator on new lines. Such marginal oversights can become quite a nuisance to correct time and time again. Fortunately, there is a rather simple pattern which can be used to help avoid these errors with very little effort – only requiring code to be rewritten in a manner that reads more naturally while also being syntactically correct.

Typical missing comma scenario

If we are to consider the most common scenario where a comma is unintentionally omitted (and a subsequent exception is thrown), it can most likely be found within The Single var Pattern (irrespective of any personal preference towards or against the pattern itself).

For example, consider a typical block of code implementing a single var:

The above example, being rather typical and admittedly simple, does not pose much of a maintenance issue itself. However, if one is to refactor these declarations into a different order, add additional declarations, or specify more complex assignments, the probability of a comma being omitted unintentionally or becoming out of place increases.

In addition to The Single var Pattern, object literals are also a good source of occasional commas being omitted unintentionally, especially when nested within additional literals:

A Simple Solution

To help avoid such mistakes altogether, we can simply place commas before declarations, rather than after. At first, this may feel a bit awkward, but in time it becomes quite easy to get used to.

With this in mind, by placing commas first, the above could easily be refactored to the following:

As can be seen in the above example, considering we generally read code left to right, it becomes immediately apparent if a comma is missing.

For instance, take note of which implementation is easier to notice the missing comma:

I suspect most would agree that commas placed before stand out much more, and therefore it becomes much more apparent when one is missing. This appears to be so as the difference between the two is such that with commas placed after one needs to look for what is missing, whereas with commas placed before one sees what is missing.

As humans, our tendency towards patterns in general, and visual patterns in particular can not be understated. As developers, considering patterns are a significant part of our work, we should strive to take advantage of the most natural ones especially, even for things as seemingly marginal as placing comma separators first.

Decoupling Backbone Modules

One of the principle design philosophies I have advocated over the years, especially through various articles on this site, has been the importance of decoupling. And while I could go into significant detail to elaborate on the importance of decoupling, suffice it to say that all designs – from simple APIs to complex applications – can benefit considerably from a decoupled design; namely, with respect to testability, maintainability and reuse.

Decoupling in Backbone

Many of the examples which can be found around the web on Backbone are intentionally simple in that they focus on higher level concepts without diverging into specific implementation or design details. Of course, this makes sense in the context of basic examples and is certainly the right approach to take when explaining or learning something new. Once you get into real-world applications, though, one of the first things you’ll likely want to improve on is how modules communicate with each other; specifically, how modules can communicate without directly referencing one another.

As I have mentioned previously, Backbone is an extremely flexible framework, so there are many approaches one could take to facilitate the decoupling of modules in Backbone; the most common of which, and my preferred approach, is decoupling by way of events.

Basic Decoupling with Events

The simplest way to facilitate communication between discreet modules in Backbone is to have each module reference a shared event broker (a pub /sub implementation). Modules can register themselves to listen for events of interest with the broker, and modules can also communicate with other modules via events as needed. Implementing such an API in Backbone is amazingly simple, in fact, so much so that the documentation provides an example in the following one liner:

Essentially, the dispatcher simply clones (or alternately, extends) the Backbone.Events object. Different modules can reference the same dispatcher to publish and subscribe to events of interest. For example, consider the following:

In the above example, the Users Collection is completely decoupled from the UserEditor View, and vice-versa. Moreover, any module can subscribe to the 'users:add' event without having any knowledge of the module from which the event was published. Such a design is extremely flexible and can be leveraged to support any number of events and use-cases. The above example is rather simple; however, it demonstrates just how easy it is to decouple modules in Backbone with a shared EventBroker.

Namespacing Events

As can be seen in the previous example, the add event is prefixed with a users string followed by a colon. This is a common pattern used to namespace an event in order to ensure events with the same name which are used in different contexts do not conflict with one another. As a best practice, even if an application initially only has a few events, the events should be namespaced accordingly. Doing so will help to ensure that as an application grows in scope, adding additional events will not result in unintended behaviors.

A General Purpose EventBroker API

To help facilitate the decoupling of modules via namespaced events, I implemented a general purpose EventBroker which builds on the default implementation of the Backbone Events API, adding additional support for creating namespace specific EventBrokers and registering multiple events of interest for a given context.

Basic Usage

The EventBroker can be used directly to publish and subscribe to events of interest:

Creating namespaced EventBrokers

The EventBroker API can be used to create and retrieve any number of specific namespaced EventBrokers. A namespaced EventBroker ensures that all events are published and subscribed against a specific namespace.

Namespaced EventBrokers are retrieved via Backbone.EventBroker.get(namespace). If an EventBroker has not been created for the given namespace, it will be created and returned. All subsequent retrievals will return the same EventBroker instance for the specified namespace; i.e. only one unique EventBroker is created per namespace.

Since namespaced EventBrokers ensure events are only piped thru the EventBroker of the given namespace, it is not necessary to prefix event names with the specific namespace to which they belong. While this can simplify implementation code, you can still prefix event names to aid in readability if desired.

Registering Interests

Modules can register events of interest with an EventBroker via the default on method or the register method. The register method allows for registering multiple event/callback mappings for a given context in a manner similar to that of the events hash in a Backbone.View.

Alternately, Modules can simply define an “interests” property containing particular event/callback mappings of interests and register themselves with an EventBroker

For additional examples, see the backbone-eventbroker project on github.

Testing Handlebars Helpers with Jasmine

For some time now, I have primarily been using logic-less templating solutions as they allow for a greater separation of concerns in comparison to many of their logic-based counterparts. By design, the decoupling of logic-less templates imparts greater overall maintainability in that templates become considerably less complex, and therefore, considerably easier to maintain and test.

Handlebars, my preferred logic-less templating engine, simplifies testing even further via it’s elegant Helper API. While Handlebars may not be the fastest templating solution available, I have found it to be the most testable, reusable and thus, maintainable.

Custom Handlebars Helpers

Since Handlebars is a logic-less templating engine, the interpolation of values which require logical operations and/or computed values is facilitated via Helpers. This design is quite nice in that template logic can be tested in isolation from the context in which it is used; i.e. the templates themselves. In addition to the common built-in Block Helpers, custom Helpers can easily be registering in order to encapsulate the logic used by your templates.

Registering Custom Helpers

Registering Custom Helpers is as simple as invoking Handlebars.registerHelper; passing the string name of the helper which is to be registered, followed by a callback which defines the actual helpers implementation.

Consider the following custom Helper example, which, given a string of text, replaces plain-text URLs with anchor tags:


As can be seen in the above example, custom Handlebars Helpers are registered outside the context of the templates in which they are used. This allows us to test our custom Helpers quite easily.

Testing Custom Helpers

Generally, I prefer to abstract testing custom Helpers specifically, and test the actual templates which use the Helpers independently from the Helpers. This allows for greater portability as it promotes reuse in that common custom Helpers (and their associated tests) can then be used across multiple projects, regardless of the templates which use them. While one can test Handlebars implementation code with any testing framework, in this example I will be using Jasmine.

Essentially, testing Custom Helpers is much the same as testing any other method. The only point to be noted is that we first need to reference the helper from the Handlebars.helpers namespace. Ideally this could be avoided as, should the namespace happen to change, so, too, will our tests need to change. That being said, the probability of such a change is unlikely.

Using the above example, in a Jasmine spec, the enhance helper can be referenced as follows:

Then we can test that the helper was registered:

We can then test any expectation. For example, the enhance helper should return a Handlebars.SafeString. We can test this as follows:

The enhance helper is expected to replace plain-text URLs with anchor tags. Before testing this, though, we should first test that it preserves existing markup. In order to test this use-case, we first need to access the return value from our custom Helper, we can do this by referencing the string property of the Handlebars.SafeString returned by our Helper:

Finally, we test that our enhance Helper replaces URLs with anchor tags using the above techniques:


We now have a complete test against our custom Helper, and all is green:
Custom Helper Spec
Note: The above Spec Runner is using the very nice jasmine.BootstrapReporter

And that’s all there is to it. You can fork the example at handlebars-helpers-jasmine.

Integrating Handlebars Templates in Kendo UI

I have been evaluating Kendo UI recently for its rich set of Widget APIs and general HTML5 UI Framework capabilities. One of the first things I wanted to see was how easily Kendo UI Widgets could be integrated with different Templating Engines, Handlebars in particular.

By default, Kendo UI provides out of the box templating support via Kendo UI Templates as well as support for jQuery Templates. While both solutions are quite good, I generally prefer logic-less Templating, with Handlebars being my preferred Template Engine of choice.

Fortunately, as it turns out, integration with Handlebars is actually quite simple. In fact, integration with basically any Template Engine is rather straight forward and can be implemented transparently.


In order to use a Template Engine which is not supported by default, one just needs to implement a Widget’s specific template property as a method which returns the resulting markup from a compiled template. This is easiest to understand by viewing examples in the context of both default templating as well as specific template integration.

First, templates in Kendo UI are typically implemented as follows (with this particular example being in the context of the rowTemplate of the Kendo UI Grid):

Note that in the above example the compiled template is directly assigned to the rowTemplate property.

Now, to integrate a Template Engine of your choosing (in this example, Handlebars), assign a function to the rowTemplate property. The function assigned accepts a data object (which represents the data of a row) and, simply invoke the complied template with the data object, returning the result as follows:

And thats all there is to it. You can try the above example implementation here.