You are currently browsing the Backbone archives.

Quick Tip: Backbone Collection Validation

Sunday, January 19th, 2014

Often times I find the native Backbone Collection implementation to be lacking when compared to it’s Backbone.Model counterpart. In particular, Collections generally lack in terms of direct integration with a backend persistence layer, as well as the ability to validate models within the context of the collection as a whole.

Fortunately, such short comings can easily be circumvented due to the extensibility of Backbone’s design as a generalized framework. In fact, throughout my experience utilizing Backbone, I can assert that there has yet to be a problem I have come across which I was unable to easily solve by leveraging one of the many Backbone extensions, or, more often than not, by simply overriding Backbone’s default implementation of a given API.

Validating Collections

Perhaps a common use-case for validating a collection of Models can be found when implementing editors which allow for adding multiple entries of a given form section (implemented as separate Views), whereby each section has a one-to-one correlation with an individual model. Rather than invoke validation on models from each individual view, and manage which model’s are in an invalid state from the context of a composite view, it can be quite useful to simply validate the collection from the composite view which, in turn, results in all models being validated and their associated views updating accordingly.

Assuming live validation is not being utilized, validation is likely to occur when the user submits the form. As such, it becomes necessary to validate each model after their views have updated them as a result of the form being submitted. This can be achieved quite easily by implementing an isValid method on the collection which simply invokes isValid on each model within the collection (or optionally, against specific models within the collection). A basic isValid implementation for a Collection is as follows:

As can be seen in the above example, the Collection’s isValid method simply invokes isValid on it’s models. This causes each model to be re-validated which, in turn, results in any invalid models triggering their corresponding invalidation events, allowing for views to automatically display validation indicators, messages, and the like; particularly when leveraging the Backbone.Validation Plugin.

This example serves well to demonstrate that, while Backbone may not provide everything one could ever ask for “out of the box”, it does provide a design which affords developers the ability to quickly, easily, and effectively extend the native framework as needed.

Function Modules in RequireJS

Wednesday, October 16th, 2013

Having leveraged RequireJS as part of my preferred client-side web stack for some time now, I find it rather surprising how often I recall various features from the API docs which I have yet to use, and how they may apply to a specific solution I am implementing.

One such feature is the ability to define a module as a function. While at first this may seem a rather basic feature, and indeed it is, there are quite a few practical purposes in which returning a function as a module definition can prove useful.

Function Modules

As one may expect, returning a function as a Module in RequireJS is rather straight-forward. For example, a simple random function can be defined as a module as follows:

Then, the function module can simply be invoked as follows:

Function Modules as Factories

Perhaps a more practical example of implementing a function module is in the context of a Factory Method.

For instance, a function module can be used as a convenient means of creating a specific type of object on a clients behalf based on certain conditions.

Take (an intentionally simple) example of a function module which, given a specific role type, returns a corresponding view implementation (in this example, a Backbone View) for an Editor feature:

Client code can then simply invoke the factory in order to retrieve the appropriate Editor view implementation based on the specified role type:

Defining modules as functions which serve as factory methods can help simplify client code implementations, as the responsibility of determining the type of object to create, configure, etc., can be delegated to a dedicated object; thus allowing for simpler designs which better facilitate code reuse, testing, and maintenance.

As a general rule of thumb, I typically reserve implementing modules as functions for cases in which a package level method would be appropriate, or for factory implementations. However, there are other scenarios in which function modules may apply, and so they are certainly worth noting.

You can fork the above example here.

Pseudo-abstraction in Backbone

Thursday, May 2nd, 2013

As has been mostly disseminated, JavaScript, being a dynamic, prototypal language, affords developers the ability to design outside the rigid confines inherent to statically typed languages. Interestingly, perhaps even somewhat paradoxically, this same flexibility also allows for programmatically simulating specific features commonly found in statically typed languages, if desired.

While JavaScript does not have a traditional type system, nor does it provide traditional constructs by which user defined types are specified, it is still, necessarily so, a common and desirable design goal to implement a system with the notion of classes in order to provide data types which encapsulate domain logic and facilitate reuse; both of which being key design attributes which help mitigate the complexity of large applications.

Nearly all JavaScript MV* frameworks provide such facilities, and do so in a consistent and convenient manner; most of which allowing for practical circumvention of the prototype system almost entirely. It is also worth noting that while most libraries themselves are generally implemented in the succinct and terse, large applications typically call for a more traditional object oriented design, while also being prudent to do so in alignment with the conventions and idioms particular to JavaScript itself.


At times it will be necessary to design a system with reusable abstractions. In fact, it is quite hard to imagine a modern SPA of even marginal complexity as being maintainable without some level of base class functionality.

For instance, it can be particularly useful to implement base Models and Collections which provide general functionality common amongst all Models and Collections; such as the parsing and appropriate routing of service API exceptions to error callbacks, and successful service results to success callbacks, and so forth.

Since such base classes generally do not provide any concrete behaviors themselves (hence the abstraction), they are of considerable value, specifically when reused amongst various large scale, distributed projects; and, from a design perspective, it is often important for one to ensure such classes are only used as intended.

While one can convey the intended usage of a base class easily enough simply by means of comments alone, indicating their usage as such (and that is quite fine if you prefer), it is also just as easy to ensure base classes are only used as intended programmatically by implementing a simple conditional which checks an instance’s constructor against the base class’ constructor function. For example (in the context of backbone, though any framework applies):

Then, one can simply extend the base class, invoking defaults as needed:

Concluding Thoughts

Like many in the JavaScript community, I, too, am of the opinion that JavaScript should not be made to reflect that which is common to other languages simply for the sake of familiarity; but rather, one should be prudent to leverage the flexibility inherent to the language itself, and this example serves as a demonstration of how such flexibility can be utilized to provide what a specific design calls for at the discretion of the developer.

Determining if an object is empty with Underscore / Lo-dash

Saturday, August 18th, 2012

When leveraging the utilities provided by Underscore or Lo-dash, determining if an Array, String or Object is empty is quite simple via the isEmpty() method.

The isEmpty() method and Objects

In the context of an Object, it is important to keep in mind that _.isEmpty() is implemented such that it determines an Object as being empty in a literal sense. That is, objects are traversed to determine the existence of any own properties – irrespective of their actual values. Thus, _.isEmpty() will return false if an object contains any own properties, even if all property values are undefined, otherwise it will return true.

While these details may seem obvious, it is important to be mindful of them in order to avoid potential false positives when trying to determine if an object’s properties are all undefined.

For example, consider the following object:

Technically, the above object is not empty, as it contains two own properties. Thus, invoking _.isEmpty() with this object will return false, which is correct, though one may have mistakenly assumed it to have returned true since all of the object’s properties are undefined.

Extending Underscore / Lo-dash

With an understanding in mind of how _.isEmpty() is implemented in the context of objects, should one need to determine if an object is empty based on the values of it’s own properties being undefined, a simple extension, such as the following, can be mixed into Underscore or Lo-dash to provide both the default implementation as well as an extended implementation which takes this into account:

Given the above, we can then invoke the original isEmpty implementation, as well as the extended implementation as follows:

The ease with which libraries such as Underscore and Lo-dash allow for adding extensions and overriding default implementations is a key design feature which makes them not only extremely flexible, but also quite enjoyable to work with as well.

Managing Client-side Templates with RequireJS

Sunday, July 15th, 2012

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

Wednesday, April 18th, 2012

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.