Refactoring Notestream With Backbone.js

For the past 3 months I have been working with Backbone.js. Specifically, refactoring my thesis project Notestream as a single page application. I’d like to share a couple insights. Note: I did not include Marionette with this project.

Refactoring this project gave me perspective on whether it’s worthwhile to use a clientside framework. Will you have to maintain the project in the future? Are there a lot of moving parts? Then yes, a framework will probably be useful. Regardless, I highly recommend building a static version of the web app first before incorporating a framework. This way you’ll know how to split out your views and organize your data structures.

The biggest positives for using Backbone with this project are:

  • Splitting DOM elements out from data through templating.
  • Not having to manually poll the server. Events trigger communication with the server now.
  • A single page application feels very snappy

RequireJS

To keep the my code as modularized as possible, I incorporated RequireJS. This way I was able to split out all my code and markup into seperate files, and use them when necessary. Organizing your application using Modules by Thomas Davis as well as Jeffrey Way’s video tuturial do a great job explaining how to use the two in tandem.

One thing to note that was not covered in the tutorials, is the ability to set up your modules a la nodeJS like so:

define(function(require) {
  var Backbone = require('lib/backbone'),
      nestedView = require('views/nestedView')
      demoTemplate = require('text!../../templates/demoView.html');

  // demo view code...
});

Instead of seperately definining your modules and declaring the function:

define(["lib/backbone", "views/nestedView" , "text!../../templates/demoView.html"],
  function(Backbone, nestedView, demoTemplate) {
    // demo view code ...
  }

You can imagine if you have multiple modules, for example many nested views, how the former setup is is better organized. Another potential headache with the latter is the function arguments have to match the order of the modules being defined. Again, that’s solved using variables.

Authentication

One area I had some difficulty with a how to implement authentication with a single page app. I have not seen a lot of detailed tutorials or example code on implementing authentication along with Backbone.js.

For now, I am using seperate routes for authentication with Passport.js, while the Notestream app itself is a single page app.

Comments