Sunday, October 20, 2013

The Ultimate BackBone Crash Course

Part one:  the 30,000 ft view

The following is an extremely simplified and slightly snarky synopsis of the popular Backbone JavaScript “framework.”  I hope to give a high level view of:
  1. What Backbone.js actually is
  2. What is in it
  3. Where to go from here
But in short, this is written for those brand new to the very powerful JavaScript toolkit so that they will have a high level view of what it offers before being tempted to dive into the incredibly joyous dearth of information that is the official backbone documentation.


What is Backbone.js

Backbone is often referred to as a JavaScript "framework" but it is not a framework like the other 3 leading frameworks[1] are in that it will not tell you exactly how to use it.  It is officially a library but that might imply it is as vast as one of the libraries it is built on, Jquery.  So I contend, it is really a toolkit consisting of a handful of powerful classes that might serve as the brains of your of the monster you want to build while also facilitating a pub-sub system to serve as the joyous nerve center of said monster.  In fact, I am pretty sure that is why it was called “backbone.”

That and, if you plan to only use this "framework" and not invent any of your own conventions to properly design your own system, then your evolving beast will likely become a weak and vulnerable beast waiting to be eaten by the evils of long term maintenance.


So farcical analogies aside, what exactly is backbone.js?

Backbone is a JavaScript toolkit that facilitates a type of  MVC(kinda) . .  & R . . with an A&E .. architecture. 

By that, I mean that Backbone provides the base classes you might use to follow the well-known MVC (Model View Controller) architecture  . . . except it does not officially have a controller.  Much of those official roles are often covered in the View classes.  But it does have a Router that serves some of the official Controller functions, thus it is actually an example of the trendy MV* (a.k.a. M-V-Star) architecture.  However, many who use backbone often feel the need to implement their own Application level object(s) and we cannot forget the high speed bus of backbone to organize its pub-sub methodologies, the Event class.  So Backbone.js a little more than a way to facilitate MV*.

Therefore,  I am dubbing backbone an MV*ea (or M-V-Starry) JavaScript Toolkit.

I realize you are now tremendously impressed with my ability to create new terminology, but I dare you to unlearn that mnemonic.  I dare you!


So let’s discuss this short list of powerful classes and the primary purposes they serve.


What is in it

The “Model” of the MV* software architecture pattern within Backbone is made up of model objects and collection objects.  Instances of the model are largely dumb objects that might manage some of your most basic ajax calls and they also initiate themselves in a clever manner.  But they really just hold data.  The collection objects are made up of a list of the same model objects instantiated from the same class.  They are also just a tad bit shrewder than models and are a more likely location to house code that retrieves large amounts of data from the server through the “fetch” or “sync” calls.  This is also usually the best place to abstract any browser side filtering of said data.  As these classes often reflect your data structure on the back-end, they are easily organized and often well contained.  However, in contrast, the View classes are usually a complete mess.

The View classes, of course, manage all the logic of displaying the UI ideally through the use of templates.  As Backbone is built on Underscore (which is built on JQuery) there are a couple standard templating systems easily available.  However, the View objects also must manage the events originating from the user and dynamic updates to these templates.  In plain Backbone (IE: not using a framework like Marionette), some Views often have to manage other sub-Views. This can get very confusing and lead to a lot of repeated “boiler-plate” code.  So to sum up, View classes do a whole lot and it is quite easy to make a complete mess out of said classes.



Fortunately Routers are quite simple.  They map a URL, including any parameters that might be involved, to one specific function often called an action.  These actions often involve creating Models and/or Collections plus initiating the server communications needed to be sure these pieces of data are valid.  These objects are then passed to new View instances.  So in most cases, the routers are the masters of instantiation.

Please note that how you organize the Routers is really up to you.  You could have one massive router for the whole system or you could have one router for every major server interaction in your system or every step in your workflow.  However, it often makes a lot of sense to organize your actions into different routers analogously to how you organize your workflow.  Life is just so much simpler when you know where everything is.



Lastly, Backbone provides a simple class to handle messaging (or pub-sub) within your system based on the Events class.  As long as one corner of the system is “listening” for the same message that another corner “triggers,” then you can manage responses to all sorts of actions at any given time.  This is especially useful when managing asynchronous events such as responses from the server or interactions from the user.

Please note Events are an example of a “use at your own risk” type of tool.  For instance, it is very easy to create two contradictory responses to the same message or to initiate a response to an action long after the context is appropriate but we will save that discussion for some sort of “pitfalls” posting later.  My only suggestion is to have some guidelines set for your application's use of events or Spaghetti may come to bite you.



Where to Go from Here

So despite the fact that this post is rather short, this really does sum up all the major components of Backbone.js.  Obviously there will be many lessons to be learned from your first major project, which is why I hope to post a list of “pitfalls” to avoid at some point.  I should also admit that much of my time as a Backbone developer has been whilst under the protection of Derick Bailey’s Marionnette version of Backbone.  The many reasons that this more structured form of Backbone is completely bad ass will also be saved for another post, but it’s fair to say that those that are using backbone the old fashioned way will have a different perspective than myself.  In fact, I would appreciate any comments on my ramblings in the interest of knowledge sharing.

But most importantly, if you are not going to use someone else's framework, I strongly suggest you come up with at least some standards for how you are going to solve repeated problems.  If you don't know what problems I am referring to, please rethink your decision to not use a backbone framework.

This author would like to thank his Cousin John Cardoza (AKA the Nevada Traveler) for teaching him to be snarky whilst writing on obscure topics.  Rewqls.




[1]Conversations in Silicon Valley generally give BackBone, Ember, Knockout and Angular credit for the top four spots in the charts.  If you disagree, pls comment below.

4 comments:

  1. Good stuff. I hadn't heard of Marionette, so I went and looked at it after this post!

    Some of the parallels between Rails and the various JS frameworks are interesting. Yehuda Katz had a teardown of MV* at the most recent GoGaRuCo ("http://confreaks.com/videos/2674-gogaruco2013-a-tale-of-two-mvc-s"). He had an axe to grind that basically boiled down to "just do MVC on the JS side and use Rails as an app server and the complexity isn't high", but his breakdown of similar framework concerns was great.

    ReplyDelete
    Replies
    1. Noah, Thank you so much for the appreciation and especially the insight. As a front-end focused engineer, the Katz approach seems almost obvious to me but I am quite biased. Having some one with his resume explain it provides much needed amo.

      Delete
  2. Very cool writeup! Thanks! Backbone indeed does not come with much blueprints, and you have to experiment quite a lot for yourself how to make sense out of Backbone for your use cases. One of the powerful things in Backbone, is the ecosystem of plugins and if you ever need to layout a large scale application with Backbone, you might also want to take a look at: https://github.com/walmartlabs/generator-thorax

    ReplyDelete
    Replies
    1. Thank you very much for the encouragement! And I appreciate you bringing Thorax to my attention. I am a big proponent of Marionette, but even its creator acknowledges Thorax as a very respectable alternative: http://lostechies.com/derickbailey/2012/06/13/why-should-i-use-backbone-marionette-instead-of-%E2%80%A6/

      Delete