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.EventsvarCranium=Cranium||{};// Set DOM selection utilityvar$=document.querySelector.bind(document)||this.jQuery||this.Zepto;// Mix in to any object in order to provide it with custom events.varEvents=Cranium.Events={// Keeps list of events and associated listenerschannels:{},// CountereventNumber:0,// Announce events and passes data to the listeners;trigger:function(events,data){for(vartopicinCranium.Events.channels){if(Cranium.Events.channels.hasOwnProperty(topic)){if(topic.split("-")[0]==events){Cranium.Events.channels[topic](data)!==false||deleteCranium.Events.channels[topic];
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access