Compass In Hand

Guiding The Geek In You

Category Archives: Backbone JS


How to Build a Project Sandbox

Sometimes the hardest part about a project is sitting down to organize your environment before you begin. Sure, you probably have several, maybe hundreds, of pieces of functional code stashed in your git repo or squirreled away in different folders on your hard drive, but starting a brand new project? Ugh! Enter the project sandbox.

Why a Project Sandbox?

Project sandboxes are templates designed for easy duplication that allow you to quickly create an ideal project environment. Pre-configured folder structures and file names optimized to your liking make launching a new project as easy as duplicating a template and making a tweak to the new project’s server config file.

Similar to regular sandboxes – also known as development servers – project sandboxes isolate projects to a well-defined structure, preventing code pollution. The key difference is Sandboxes are usually designed for developing within an existing code base protected by a code repository. Project sandboxes, however, exist only to help start new and potentially disposable development in a reliable way.

Naming schemes

Regarding naming schemes: the word of the day is CONSISTENCY. Name your project sandbox files anything you like and commit to your scheme. When you find a better naming method (and you will), retrofit your project sandbox right away – don’t put it off! Using consistent file names will build strong mental associations that help you decide where to put certain code.

My project sandbox files:

  • main.js
  • main.css
  • index.html

Some file stubs (files that exist without any content) I like keeping handy to handle RWD needs, or to load AMD formatted scripts, respectively:

  • responsive.css
  • requireLoader.js

Being Flexible

Flexibility in terms of a project sandbox means keeping a variety of battle tested and carefully vetted resources at your finger tips, not all of which you may need for every project. Some resources should be configured to load by default, while others (like frameworks) are kept out of the loading stack.

Some of my core resources:

General Tools

Asynchronous Resource Loaders

JS MVC Frameworks

JS Libraries

  • Underscore.js
  • jQuery (keep a couple of versions handy – load one by default)
  • Zepto.js (lighter weight than jQuery, better for mobile devices)
  • [Your Favorite jQuery Plug-ins Here]

CDN vs Locally Stored Resources

Should you use a CDN or keep your toolkit stored locally? I prefer using local files. Staying local removes a layer of potential complexity (not relying on a file that probably stays the same), improves performance, and keeps resource files readily available for dissection. That said, CDNs are extremely valuable in many other situations.

However, using local resources means you must manually keep your project sandbox current. Get into the habit of watching for updates, reading release notes, and making informed decisions about updating your resources. Broken and dull tools are even worse than no tool at all!

Folder Organization

Folder organization depends largely on your web server and middle tier language of choice. Discussing the best ways to organize folders for different servers and languages could be a cool topic for another day.

Since I use Node.js my project sandbox folder structure is pretty simple, as demonstrated below.

  • WEBROOT
    • TEMPLATE (this is your Project Sandbox – copy and paste at will!)
      • startServer.js (the Project Sandbox config file)
      • PUBLIC
        • index.html
        • JS
          • main.js
          • requireLoader.js
        • CSS
          • main.css
          • responsive.css
        • FONTS
        • IMG
    • RESOURCES (libraries, frameworks, often used assets – only one copy necessary)
      • JS
        • LIBRARIES
          • jQuery (development and minified versions)
          • JQUERY PLUG-INS
            • [your favorite plug-ins here]
          • Zepto.js
          • Underscore.js
        • LOADERS
          • RequireJS
          • Modernizr (includes yepnope.js)
        • FRAMEWORKS
          • AngularJS
          • Backbone
          • Ember.js
      • CSS
        • FRAMEWORKS
          • Bootstrap
      • FONTS
        • [non-web fonts used often go here]
      • IMG
        • [logos, backgrounds, etc – include only if used frequently]

Of course, this is only a start! Your project sandbox can be tailored in any way you see fit and will change over time. The important lessons are: make one, keep it consistent, keep it current.

Good luck, and please comment with any suggestions. And as always, thank you for reading!

Understanding JS MVC Frameworks

What is MVC?

Invented by Trygve Reenskaug, who originally called it the “Thing-Model-View-Editor” way back in 1979 (read all about it), the MVC design pattern has been a staple in software design since it appeared in the Smalltalk-80 class library.

Discussing software design patterns exceeds this post by light years, as does the interior magic of MVC (and siblings such as MVP, and MVVM, and so on). However, let’s cover a couple quick concepts in as non-boring-as-hell way as possible.

The MVC design pattern is focuses on “separation of concerns”. Meaning, software built using this design pattern is composed of pieces belonging to one of three main areas:

  • Data (Model)
  • Presentation (View)
  • User-Input (Control)

For example, when the user interacts with the software by changing the contents of the first name field, the controller handles the user input and changes the state of the model (which is responsible for storing that name somewhere). The controller does not directly tell the view “hey, the user changed the first name and I asked the model to save the information.” Instead the view is observing changes made to the model, and when those changes require a refresh of what the user actually observes on-screen – that refresh happens.

This is simplifying a more in-depth process – but hopefully you can appreciate how each piece has a unique role to play, and that the unity of these roles forms a very tight and reliable pattern for software design.

So…the JS MVC framework? I mean…JavaScript? Seriously?

Absolutely! JavaScript has been in circulation for years. As a language made available via almost every browser it has penetrated into a vast assortment of devices. While the wise programmer will Progressive(ly) Enhance their sites – you never know whether JS is disabled, after all – it’s a safe assumption JavaScript will be available.

Of course raw JavaScript is rarely used anymore in a de-facto sense. While there are obvious speed and precision benefits to hand-coding JS, libraries (and the ocean of plug-ins available there-in) and frameworks take JavaScript development into entirely new realms. Frameworks in particular bring a virtue to the JavaScript ecosystem that have made complex single page development practical.

Understand: when you use a framework your code rests upon and within it. There are rules that should be followed, and coloring outside the lines is discouraged – and can sometimes be disastrous. So choose your coloring book with care.

What do I look for in a JS MVC?

A quality code base and an appropriate feature list. Will the framework do what you need it to do? Do you understand what’s happening under the hood?

Has the framework been endorsed by big companies? Implementation is a great sign of endorsement – do your research, who’s using this framework?

Are other developers actively supporting the framework? How many? Are the builds coming out fast and furious? Stability is good, commitment to growth over time is even better.

Documentation is vital! A big advantage to a JS MVC framework like Backbone is the sheer number of educational resources available to the developer.

Frameworks exist on an “opinionated” scale. Some, like AngularJS and Ember.js, are tremendously opinionated and will, via convention and scaffolding, handle many basic duties on behalf of the developer. These duties can include standardized file and URL structures. Un-opinionated frameworks like Backbone leave file and URL structuring up to the developer, sometimes frameworks even ask the developer to figure out their own routing and data storage solutions.

How interoperable is this framework? If you want to gently insert pieces of a framework into your existing code base, will the framework tolerate it? Backbone is happily inserted where ever you squeeze it. AngularJS is also friendly, but prefers some control – for example AngularJS prefers (but in no way requires) its built-in jqLite over jQuery, mostly because jqLite makes unit testing easier. Ember.js, however, demands total domination. It wants to control the entire page at run time.

Consider your target audience and the devices they likely use. Now, look at the file size of your framework including all dependencies. Realize that fully featured frameworks like Ember.js come equipped with built in solutions and typically only requires a single dependency, handlebars.js. Backbone, on the other hand, despite how lightweight and un-opinionated it is, needs underscore.js and jQuery (for desktops) and / or zepto.js (for mobile) to run. These requirements add weight.

Finally, avoid the insanity caused by YAFS (Yet Another Framework Syndrome) by downloading and using the amazing TodoMVC. TodoMVC is a collection of many of the leading JS MVC frameworks and assigns a single task to each: render a handy little To-Do List application. The UI is friendly and identical between each implementation. All of the code is exposed and ready for analysis. WooHoo!

When should a JS MVC framework be used?

Consider the problems solved by a framework:

  • Two-way data binding usually between HTML and a JS object model (changes made to one bound input auto update other elements also bound).
  • View templates (string-based templates vs DOM-based templates).
  • Local or Web Server based data storage (RESTful interactions, DIY $.ajax() functions, in some frameworks disconnected states are even supported).
  • URL routing, aka “Supporting the Back Button”. Single page apps do not generate entries in a browser’s history, so hitting “back” won’t do anything – unless some sort of state tracking mechanism is in place.

Now consider the pain a framework implementation will bring:

  • Cumbersome code structure.
  • Complex conceptual rules.
  • Can force needless amounts of “code bureaucracy”.
  • “First implementation” learning curve too steep for busy teams.

Lastly, keep in mind that implementing single page applications is the core strength of the JS MVC. Therefore, if your project is a basic web page application a framework might be an over-engineered solution. I say “might” because some frameworks, like Backbone, can usefully solve common issues even in these traditional applications.

Great, framework selected. Now what?

Awesome! Go download the framework and the dependencies, then load them into your Hello World project template, just like you would a JS library. Or, if you prefer and the option is available, use the CDN made available by the framework community.

After the World has been Hello’ed adequately, study the TodoMVC implementation of your framework. Peel back the covers, read the comments, study the hell out of the source and do your best to understand what is going on. You may come to rely on the awesome magic Ember.js, AngularJS, or your MVC of choice provides – but first do your best to understand it!

Finally, start your own project. In upcoming posts I will be discussing my project, including which framework I use and why. Stay tuned, and thanks for reading!