Appendix A. Further Learning

A Simple JavaScript MVC Implementation

A comprehensive discussion of Backbone’s implementation is beyond the scope of this book. I can, however, present a simple MVC library—which we will call Cranium.js—that illustrates how frameworks such as Backbone implement the MVC pattern.

Like Backbone, we will rely on Underscore for inheritance and templating.

Event System

At the heart of our JavaScript MVC implementation is an Event system (object) based on the publisher-subscriber pattern, which makes it possible for MVC components to communicate in an elegant, decoupled manner. Subscribers listen for specific events of interest and react when publishers broadcast these events.

Event is mixed into both the view and model components so that instances of either of these components can publish events of interest.

// cranium.js - Cranium.Events

var Cranium = Cranium || {};

// Set DOM selection utility
var $ = document.querySelector.bind(document) || this.jQuery || this.Zepto;

// Mix in to any object in order to provide it with custom events.
var Events = Cranium.Events = {
  // Keeps list of events and associated listeners
  channels: {},

  // Counter
  eventNumber: 0,

  // Announce events and passes data to the listeners;
  trigger: function (events, data) {
    for (var topic in Cranium.Events.channels){
      if (Cranium.Events.channels.hasOwnProperty(topic)) {
        if (topic.split("-")[0] == events){
          Cranium.Events.channels[topic](data) !== false || 
          delete Cranium.Events.channels[topic];

Get Developing Backbone.js Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.