You are previewing Learning JavaScript Design Patterns.

Learning JavaScript Design Patterns

Cover of Learning JavaScript Design Patterns by Addy Osmani Published by O'Reilly Media, Inc.
  1. Learning JavaScript Design Patterns
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Preface
    1. Target Audience
    2. Credits
    3. Reading
    4. Conventions Used in This Book
    5. Using Code Examples
    6. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
  4. 1. Introduction
  5. 2. What Is a Pattern?
    1. We Already Use Patterns Every Day
  6. 3. “Pattern”-ity Testing, Proto-Patterns, and the Rule of Three
  7. 4. The Structure of a Design Pattern
  8. 5. Writing Design Patterns
  9. 6. Anti-Patterns
  10. 7. Categories of Design Patterns
    1. Creational Design Patterns
    2. Structural Design Patterns
    3. Behavioral Design Patterns
  11. 8. Design Pattern Categorization
    1. A Brief Note on Classes
  12. 9. JavaScript Design Patterns
    1. The Constructor Pattern
      1. Object Creation
      2. Basic Constructors
      3. Constructors with Prototypes
    2. The Module Pattern
      1. Object Literals
      2. The Module Pattern
      3. Module Pattern Variations
    3. The Revealing Module Pattern
      1. Advantages
      2. Disadvantages
    4. The Singleton Pattern
    5. The Observer Pattern
      1. Differences Between the Observer and Publish/Subscribe Pattern
      2. Advantages
      3. Disadvantages
      4. Publish/Subscribe Implementations
    6. The Mediator Pattern
      1. Basic Implementation
      2. Advanced Implementation
      3. Example
      4. Advantages and Disadvantages
      5. Mediator Versus Observer
      6. Mediator Versus Facade
    7. The Prototype Pattern
    8. The Command Pattern
    9. The Facade Pattern
      1. Notes on Abstraction
    10. The Factory Pattern
      1. When to Use the Factory Pattern
      2. When Not to Use the Factory Pattern
      3. Abstract Factories
    11. The Mixin Pattern
    12. Subclassing
    13. Mixins
      1. Advantages and Disadvantages
    14. The Decorator Pattern
    15. Pseudoclassical Decorators
      1. Interfaces
      2. Abstract Decorators
    16. Decorators with jQuery
    17. Advantages and Disadvantages
    18. Flyweight
      1. Using Flyweights
      2. Flyweights and Sharing Data
      3. Implementing Classical Flyweights
      4. Converting Code to Use the Flyweight Pattern
      5. A Basic Factory
      6. Managing the Extrinsic States
      7. The Flyweight Pattern and the DOM
  13. 10. JavaScript MV* Patterns
    1. MVC
      1. Smalltalk-80 MVC
    2. MVC for JavaScript Developers
      1. Models
      3. Controllers
      4. Controllers in Another Library (Spine.js) Versus Backbone.js
    3. What Does MVC Give Us?
    4. Smalltalk-80 MVC in JavaScript
      1. Delving Deeper
      2. Summary
    5. MVP
      1. Models, Views, and Presenters
      2. MVP or MVC?
      3. MVC, MVP, and Backbone.js
    6. MVVM
      1. History
      2. Model
      3. View
      4. ViewModel
      5. Recap: The View and the ViewModel
      6. Recap: The ViewModel and the Model
    7. Pros and Cons
      1. Advantages
      2. Disadvantages
    8. MVVM with Looser Data Bindings
    9. MVC Versus MVP Versus MVVM
    10. Backbone.js Versus KnockoutJS
  14. 11. Modern Modular JavaScript Design Patterns
    1. A Note on Script Loaders
    2. AMD
      1. Getting Started with Modules
      2. AMD Modules with Dojo
      3. AMD Module Design Patterns (Dojo)
      4. AMD Modules with jQuery
      5. AMD Conclusions
    3. CommonJS
      1. Getting Started
      2. Consuming Multiple Dependencies
      3. Loaders and Frameworks that Support CommonJS
      4. Is CommonJS Suitable for the Browser?
      5. Related Reading
    4. AMD and CommonJS: Competing, but Equally Valid Standards
      1. UMD: AMD and CommonJS-Compatible Modules for Plug-ins
    5. ES Harmony
      1. Modules with Imports and Exports
      2. Modules Loaded from Remote Sources
      3. Module Loader API
      4. CommonJS-like Modules for the Server
      5. Classes with Constructors, Getters, and Setters
      6. ES Harmony Conclusions
      7. Related Reading
    6. Conclusions
  15. 12. Design Patterns in jQuery
    1. The Composite Pattern
    2. The Adapter Pattern
    3. The Facade Pattern
    4. The Observer Pattern
    5. The Iterator Pattern
    6. Lazy Initialization
    7. The Proxy Pattern
    8. The Builder Pattern
  16. 13. jQuery Plug-in Design Patterns
    1. Patterns
    2. A Lightweight Start Pattern
      1. Further Reading
    3. Complete Widget Factory Pattern
      1. Further Reading
    4. Nested Namespacing Plug-in Pattern
      1. Further Reading
    5. Custom Events Plug-in Pattern (with the Widget Factory)
      1. Further Reading
    6. Prototypal Inheritance with the DOM-to-Object Bridge Pattern
      1. Further Reading
    7. jQuery UI Widget Factory Bridge Pattern
      1. Further Reading
    8. jQuery Mobile Widgets with the Widget Factory
    9. RequireJS and the jQuery UI Widget Factory
      1. Usage
      2. Further Reading
    10. Globally and Per-Call Overridable Options (Best Options Pattern)
      1. Further Reading
    11. A Highly Configurable and Mutable Plug-in Pattern
      1. Further Reading
    12. What Makes a Good Plug-in Beyond Patterns?
      1. Quality
      2. Code Style
      3. Compatibility
      4. Reliability
      5. Performance
      6. Documentation
      7. Likelihood of maintenance
    13. Conclusions
    14. Namespacing Patterns
    15. Namespacing Fundamentals
      1. Single Global Variables
      2. Prefix Namespacing
      3. Object Literal Notation
      4. Nested Namespacing
      5. Immediately Invoked Function Expressions (IIFE)s
      6. Namespace Injection
    16. Advanced Namespacing Patterns
      1. Automating Nested Namespacing
      2. Dependency Declaration Pattern
      3. Deep Object Extension
      4. Recommendation
  17. 14. Conclusions
  18. A. References
  19. Index
  20. About the Author
  21. Colophon
  22. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  23. Copyright
O'Reilly logo

MVVM with Looser Data Bindings

It’s not uncommon for JavaScript developers from an MVC or MVP background to review MVVM and complain about its true separation of concerns. Namely, the quantity of inline data bindings maintained in the HTML markup of a View.

I must admit that when I first reviewed implementations of MVVM (e.g., KnockoutJS, Knockback), I was surprised that any developer would want to return to the days of old where we mixed logic (JavaScript) with our markup and found it quickly unmaintainable. The reality however is that MVVM does this for a number of good reasons (which we’ve covered), including facilitating designers to more easily bind to logic from their markup.

For the purists among us, you’ll be happy to know that we can now also greatly reduce how reliant we are on data bindings, thanks to a feature known as custom binding providers, introduced in KnockoutJS 1.3 and available in all versions since.

KnockoutJS by default has a data-binding provider, which searches for any elements with data-bind attributes on them such as in the below example.

<input id="new-todo" type="text" data-bind="value: current, valueUpdate: "afterkeydown", 
enterKey: add" placeholder="What needs to be done?"/>

When the provider locates an element with this attribute, it parses it and turns it into a binding object using the current data context. This is the way KnockoutJS has always worked, allowing us to declaratively add bindings to elements that KnockoutJS binds to the data at that layer.

Once we start building Views that are no longer trivial, we may end up with a large number of elements and attributes whose bindings in markup can become difficult to manage. With custom binding providers, however, this is no longer a problem.

A binding provider is primarily interested in two things:

  • When given a DOM node, does it contain any data bindings?

  • If the node passed this first question, what does the binding object look like in the current data context?

Binding providers implement two functions:


This takes in a DOM node, which doesn’t necessarily have to be an element.


This returns an object representing the bindings as applied to the current data context.

A skeleton binding provider might thus look as follows:

var ourBindingProvider = {
  nodeHasBindings: function( node ) {
      // returns true/false

  getBindings: function( node, bindingContext ) {
      // returns a binding object

Before we get to fleshing out this provider, let’s briefly discuss logic in data bind attributes.

If when using Knockout’s MVVM you find yourself dissatisfied with the idea of application logic being overly tied into your View, we can change this. We could implement something a little like CSS classes to assign bindings by name to elements. Ryan Niemeyer has previously suggested using data-class for this to avoid confusing presentation classes with data classes, so let’s get our nodeHasBindings function supporting this:

// does an element have any bindings?
function nodeHasBindings( node ) {
    return node.getAttribute ? node.getAttribute("data-class") : false;

Next, we need a sensible getBindings() function. As we’re sticking with the idea of CSS classes, why not also consider supporting space-separated classes to allow us to share binding specs between different elements?

Let’s first review what our bindings will look like. We create an object to hold them where our property names need to match the keys we wish to use in our data classes.

There isn’t a great deal of work required to convert a KnockoutJS application from one that uses traditional data bindings to one with unobtrusive bindings by applying custom binding providers. We simply pull our all of our data-bind attributes, replace them with data-class attributes, and place our bindings in a binding object as per below:

var viewModel = new ViewModel( todos || [] ),
    bindings = {

        newTodo:  { 
            value: viewModel.current, 
            valueUpdate: "afterkeydown", 
            enterKey: viewModel.add 

        taskTooltip : { visible: viewModel.showTooltip },
        checkAllContainer : {visible: viewModel.todos().length },
        checkAll: { checked: viewModel.allCompleted },

        todos: { foreach: viewModel.todos },
        todoListItem: function() { return { css: { editing: this.editing } }; },
        todoListItemWrapper: function() { 
          return { css: { done: this.done } }; 
        todoCheckBox: function() { return { checked: this.done }; },
        todoContent: function() { return { text: this.content, event: 
        { dblclick: this.edit } }; },
        todoDestroy: function() { return { click: viewModel.remove }; },        

        todoEdit: function() { return {
            value: this.content, 
            valueUpdate: "afterkeydown", 
            enterKey: this.stopEditing, 
            event: { blur: this.stopEditing } }; 

        todoCount: { visible: viewModel.remainingCount },
        remainingCount: { text: viewModel.remainingCount },
        remainingCountWord: function() { 
          return { text: viewModel.getLabel(viewModel.remainingCount) };
        todoClear: {visible: viewModel.completedCount},
        todoClearAll: {click: viewModel.removeCompleted},
        completedCount: { text: viewModel.completedCount },
        completedCountWord: function() { 
          return { text: viewModel.getLabel(viewModel.completedCount) }; 
        todoInstructions: { visible: viewModel.todos().length }


There are however two lines missing from the above snippet: we still need our getBindings function, which will loop through each of the keys in our data-class attributes and build up the resulting object from each of them. If we detect that the binding object is a function, we call it with our current data using the context this. Our complete custom binding provider would look as follows:

    // We can now create a bindingProvider that uses 
    // something different than data-bind attributes
    ko.customBindingProvider = function( bindingObject ) {
        this.bindingObject = bindingObject;

        // determine if an element has any bindings
        this.nodeHasBindings = function( node ) {
            return node.getAttribute ? node.getAttribute( "data-class" ) : false;

    // return the bindings given a node and the bindingContext
    this.getBindings = function( node, bindingContext ) {

        var result = {},
            classes = node.getAttribute( "data-class" );

        if ( classes ) {
            classes = classes.split( "" );  

            //evaluate each class, build a single object to return
            for ( var i = 0, j = classes.length; i < j; i++ ) {

               var bindingAccessor = this.bindingObject[classes[i]];
               if ( bindingAccessor ) {
                   var binding = typeof bindingAccessor === 
                   "function" ?$data) : bindingAccessor;
                   ko.utils.extend(result, binding);               


        return result;

Thus, the final few lines of our bindings object can be defined as follows:

// set ko's current bindingProvider equal to our new binding provider
ko.bindingProvider.instance = new ko.customBindingProvider( bindings );   

// bind a new instance of our ViewModel to the page
ko.applyBindings( viewModel );


What we’re doing here is effectively defining a constructor for our binding handle, which accepts an object (bindings) that we use to lookup our bindings. We could then rewrite the markup for our application View using data classes as follows:

<div id="create-todo">
                <input id="new-todo" data-class="newTodo" placeholder=
                "What needs to be done?" />
                <span class="ui-tooltip-top" data-class="taskTooltip" style=
                "display: none;">
                Press Enter to save this task</span>
            <div id="todos">
                <div data-class="checkAllContainer" >
                    <input id="check-all" class="check" type="checkbox" data-class=
                    "checkAll" />
                    <label for="check-all">Mark all as complete</label>
                <ul id="todo-list" data-class="todos" >
                    <li data-class="todoListItem" >
                        <div class="todo" data-class="todoListItemWrapper" >
                            <div class="display">
                                <input class="check" type="checkbox" data-class=
                                "todoCheckBox" />
                                <div class="todo-content" data-class="todoContent" 
                                style="cursor: pointer;"></div>
                                <span class="todo-destroy" data-class=
                            <div class="edit'>
                                <input class="todo-input" data-class="todoEdit'/>

Neil Kerkin has put together a complete TodoMVC demo app using the above, which you can access and play around with here.

While it may look like quite a lot of work in the explanation above, now that we have a generic getBindings method written, it’s a lot more trivial to simply reuse it and use data classes rather than strict data bindings for writing our KnockoutJS applications instead. The net result is hopefully cleaner markup with our data bindings being shifted from the View to a bindings object instead.

The best content for your career. Discover unlimited learning on demand for around $1/day.