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

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.