You are viewing the Articles in the APIs Category

Invoking Native Mobile Applications with URI Schemes

In a previous article, I outlined how the native iOS Keyboard and it’s behaviors can be managed with HTML5 input types. In addition to this, iOS, Android and most A-Grade Mobile platforms implement standard URI Schemes (or parts thereof), which allow for easily launching native applications.

URI Schemes

When considering URI Schemes, more commonly (though incorrectly) referred to as protocols, one typically thinks in terms of the more ubiquitous schemes: http, ftp, file, mailto, about, data:uri and so forth. However, as with these and other common URI Schemes, there are additional schemes which allow for various practical applications in the context of Mobile Web Apps; the most common of which being the ability to invoke a platform’s native phone or messaging application, respectively.

URI Schemes and Mobile Devices

In the context of Mobile Web Applications, the tel, and sms URI Schemes are perhaps the most common and applicable; providing a simple means of invoking their corresponding native applications. The following are basic examples which work across all major mobile platforms.

The tel URI Scheme

The tel URI Scheme allows for launching a device’s native Phone application in the context of the phone number specified:

The sms URI Scheme

The sms URI Scheme allows for launching a device’s native Messaging application to send an sms message, or to send an sms message to the phone number specified:

As can be seen in the above examples, hyphens are used in the same manner as one would typically specify a phone number; however, use of visual separators are purely optional – they can be used to aid in readability if desired, but are otherwise ignored when parsing the URI.

As a general best practice, one should take care to ensure both tel and sms URI Schemes are defined in lowercase, so as to ensure portability across platforms. Additionally, it is important to note that the sms scheme is not implemented to completion against it’s formal definition on any platform (see section 2.2 of rfc5724); thus, an sms message body, or sending an sms message to multiple recipients is not supported.

While there is nothing particularly ground breaking about these URI Schemes, or technically complex for that matter, they do prove to be quite useful in the context of Mobile Web Applications. As such, they are certainly worth noting as each can be leveraged to improve the usability of an application.

Simplifying Designs with Parameter Objects

Recently, while reading the HTML5 Doctor interview with Ian Hickson, when asked what some of his regrets have been over the years, the one he mentions, rather comically so as being his “favorite mistake”, also happened to be the one which stood out to me most; that is, his disappointment with pushState; specifically, the fact that of the three arguments accepted, the second argument is now ignored.

I can empathize with his (Hixie’s) frustration here; not simply because he is one of the most influential figures on the web – particularly for his successful work surrounding CSS, HTML5, and his responsibilities at the WHATWG in general – but rather, it is quite understandable how such a seemingly insignificant design shortcoming would bother such an obviously talented individual, especially considering the fact that pushState's parameters simply could not be changed due to the feature being used prior to completion. Indeed, the Web Platform poses some very unique and challenging constraints under which one must design.

While the ignored pushState argument is a rather trivial issue, I found it to be of particular interest as I often employ Parameter Objects to avoid similar design issues.

Parameter Objects

The term “Parameter Object” is one I use rather loosely to describe any object that simply serves as a wrapper from which all arguments are provided to a function. In the context of JavaScript, object literals serve quite well in this capacity, even for simpler cases where a function would otherwise require only a few arguments of the same type.

Parameter Objects are quite similar to that of an “Options Argument” – a pattern commonly implemented by many JavaScript libraries to simplify providing optional arguments to a function; however, I tend to use the term Parameter Objects more broadly to describe a single object parameter from which all arguments are provided to a function, optional arguments included. The two terms are often used interchangeably to describe the same pattern. However, I specifically use the term Options Argument to describe a single object which is reserved exclusively for providing optional arguments only, and is always defined as the last parameter of a function, proceeding all required arguments.

Benefits

Parameter Objects can prove beneficial in that they afford developers the ability to defer having to make any final design decisions with regard to what particular inputs are accepted by a function; thus, allowing an API to evolve gracefully over time.

For instance, using a Parameter Object, one can circumvent the general approach of implementing functions which define a fixed, specific order of parameters. As a result, should it be determined that any one particular parameter is no longer needed, API designers need not be concerned with requiring calling code to be refactored in order to allow for the removal of the parameter. Likewise, should any additional parameters need to be added, they can simply be defined as additional properties of the Parameter Object, irrespective of any particular ordering of previous parameters defined by the function.

As an example, consider a theoretical rotation function which defines five parameters:

Using a Parameter Object, we can refactor the above function to the following:

Should we wish to remove a parameter from the function, doing so simply requires making the appropriate changes at the API level without changing the actual signature of the function (assuming of course, there are no specific expectations already being made by calling code regarding the argument to be removed). Likewise, should additional parameters need to be added, such as a completion callback, etc., doing so, again, only requires making the appropriate API changes, and would not impact current calling code.

Additionally, taking these potential changes as an example, we can also see that with Parameter Objects, implementation specifics can be delegated to the API itself, rather than client code insofar that the provided arguments can be used to determine the actual behavior of the function. In this respect, Parameter Objects can also double as an Options Argument. For example, should the arguments required to perform a 3D rotation be omitted from the Parameter Object, the function can default to a 2D rotation based on the provided arguments, etc.

Convenience

Parameter Objects are rather convenient in terms of there being less mental overhead required than that of a function which requires ordered arguments; this is especially true for cases where a function defines numerous parameters, or successive parameters of the same type.

Since code is generally read much more frequently than it is written, it can be easier to understand what is being passed to a function when reading explicit property names of an object, in which each property name maps to a parameter name, and each property value maps to parameter argument. This can aid in readability where it would otherwise require reading the rather ambiguous arguments passed to a function. For example:

With Parameter Objects it becomes more apparent as to which arguments correspond to each specific parameter:

As mentioned, if a function accepts multiple arguments of the same type, the likelihood that users of the API may accidentally pass them in an incorrect order increases. This can result in errors that are likely to fail silently, possibly leading to the application (or a portion thereof) becoming in an unpredictable state. With Parameter Objects, such unintentional errors are less likely to occur.

Considerations

While Parameter Objects allow for implementing flexible parameter definitions, the arguments for which being provided by a single object, they are obviously not intended as a replacement for normal function parameters in that should a function need only require a few arguments, and the function’s parameters are unlikely to change, then using a Parameter Object in place of normal function parameters is not recommended. Also, perhaps one could make the argument that creating an additional object to store parameter/argument mappings where normal arguments would suffice adds additional or unnecessary overhead; however, considering how marginal the additional footprint would be, this point is rather moot as the benefits outweigh the cost.

A Look at pushState’s Parameters

Consider the parameters defined by pushState:

  1. data: Object
  2. title: String
  3. url: String

The second parameter, title, is the parameter of interest here as it is no longer used. Thus, calling push state requires passing either null or an empty String (recommended) as the second argument (i.e. title) before one can pass the third argument, url. For example:

Using a Parameter Object, pushState could have been, theoretically, implemented such that only a single argument was required:

  1. params: Object
    • data: Object
    • title: String
    • url: String

Thus, the ignored title argument could be safely removed from current calling code:

And simply ignored in previously implemented calls:

As can be seen, the difference between the two is quite simple: the specification for pushState accepts three arguments, whereas the theoretical Parameter Object implementation accepts a single object as an argument, which in turn provides the original arguments.

Concluding Thoughts

I certainly do not assume to understand the details surrounding pushState in enough detail to assert that the use of a Parameters Object would have addressed the issue. Thus, while this article may reference pushState as a basic example to illustrate how the use of a Parameter Object may have proved beneficial, it is really intended to highlight the value of using Parameter Objects from a general design perspective, by describing common use-cases in which they can prove useful. As such, Parameter Objects provide a valuable pattern worth considering when a function requires flexibility.

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.

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.

Persisting Backbone Collections

Backbone.js provides a light-weight, extensible API which focuses primarily on general structure, and the utility of that structure, without requiring a rigid adherence to specific patterns or prescribing certain design philosophies. This focused approach affords developers a significant level of flexibility which can prove to be essential to the success of many modern client side web applications – especially when considering the challenges surrounding the ever changing landscape of the web.

Naturally, it follows that such flexibility imparts additional responsibility on the developer. In my experience with architectural frameworks in general, and Backbone in particular, many times this kind of trade off can be quite preferable.

Extending Backbone

As mentioned above, Backbone implements the essential building blocks necessary to provide general structure within an application. If a feature is needed which is not provided by default, by design, Backbone allows for easily extending the core APIs in order to implement additional features as needed. In fact, developers are encouraged to do so.

Perhaps a good example of this can be found in the need to persist collections in Backbone; that is, interestingly, while the Backbone Model API implements a default save method, the Backbone Collection does not provide a similar API for explicitly saving the models within a collection; that is, saving the collection itself. This feature may have been left out intentionally as part of an initial design decision, as there are some complexities to saving an entire collection as a general use-case; such as saving deltas, propagating saved state to models within the collection and so forth; or, perhaps it simply may have been an oversite. Regardless of the reason, in certain scenarios it can be useful to save an entire collection rather than saving each model individually – fortunately, given the flexibility of Backbone, writing an extension to implement this feature is quite simple.

The PersistableCollection

As a basic solution for saving a Backbone Collection, I wrote a general abstraction – PersistableCollection, which extends Backbone.Collection, implementing a default save method.

The PersistableCollection API is quite simple in that it essentially just implements a proxy which wraps the collection in a Backbone Model, and ensures there is only one proxy created per collection. The url and toJSON methods, respectively, of the proxy Model reference the url and toJSON methods of the collection to which the proxy is bound. You can either extend PersistableCollection or generate a proxy for an existing collection via the static createProxy method. Examples of each follow.

Using a PersistableCollection

A PersistableCollection can be instantiated and used directly, just like a Backbone.Collection:

Extending PersistableCollection

You can extend PersistableCollection and simply invoke save to persist the models in the collection:

Creating a proxy for an existing collection

An existing collection can be saved by creating a proxy for it:

The PersistableCollection can be used as a general extension for saving entire collections based on the representation of all models within the collection. If you are interested in extending it to account for more specific use-cases, you can simply override the default save implementation as needed.

You can find the gist for the source and spec here.

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:

(Gist)

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:

(Gist)

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.