Instrumenting Backbone for better error handling

At work, we’ve been having some issues tracking down some nasty client side bugs. We know they’re happening in our Backbone views, but we’ve been unable to locate them with any more accuracy due to the errors bubbling all the way to the window.onerror handler.

Enter Stackbone. A simple bit of code to instrument Backbone’s event loops to better locate client side errors.

To use:

  Backbone: Backbone
  jQuery: jQuery
  onError: function (err) {
    // ... log the error ...

You can use Stackbone = require(‘stackbone’) or simply include the .js file in a script tag. Enjoy!


Docco Fork – All JS, all the time

EDIT: My fork is no longer needed. The folks at docco saw the same thing, and recently ported over the library to use highlight.js.

I love documentation generators for code. You know what I’ve talking about to – something which gives you a split screen of the code and the comments, side by side, for easy reading and scrolling. Like jasmine uses for their documentation:

Since I’ve mostly been working in JavaScript lately, I’ve been looking for something to help document the packages I create easily.

In comes docco. A CoffeeScript + Python library to help generate good-looking documentation from comments in your code.

However, one thing bothered my about this project – the python part. Docco uses a python library to highlight the syntax. There are plenty of decent syntax highlighters out there – why not use one written in a JavaScript flavor?

So I decided to fork docco and plugin a decent highlighter.

Pretty happy with the results. You can check out the fork here.

Esvalidate Library – Standalone Validation Library Using Esprima

I spent a good bit of time working on the Esvalidate code that comes with Esprima, trying to get it to work smoothly with my sublime plugin. After submitting a massive pull request to the author of Esprima, and our reviewing my code, we came to a conclusion – the new code was better served in its own library.

It’s still in its early stages, but please check out the progress I’m making here:

Esvalidate Library

Esprima Plugin for Sublime Text

In relation to my previous posts confessing my love for sublime, and my enjoyment of Esprima, here is some code that showcases both:

An Esprima plugin for Sublime Test!

This has been included in the official list of Sublime Plugins. So you can install this from Sublime using Packages Control.

Sublime Text – Esprima Plugin Screenshot

Added JavaScript syntax checking via Esprima and a Git pre-commit hook

I came across a brilliant project the other day – Esprima from Ariya Hidayat, the author of PhantomJS.

What is Esprima? Esprima is a JavaScript Parser written in JavaScript Syntax Validator. It forms the basis of several different tools – a minifier, a code coverage tool, a syntax validator – just to name a few.

I was immediately interested in the syntax validation tool. It’s not a linter – it just checks that the JavaScript written is syntactically correct. Why would you want this if you already have JsHint and JsLint?

  1. It is extremely fast. Validating three.js (800 KB source) takes less than a second on a modern machine.
  2. It looks only for syntax errors, it does not care about coding style at all.
  3. It handles generated files as the result of minification or compilation (CoffeeScript, Dart, TypeScript, etc).
  4. It tries to be tolerant and not give up immediately on the first error, especially for strict mode violations.

Esprima is available as an npm package, so installing it only takes a second:

sudo npm install -g esprima

Using Esprima from the command line is simple:

esvalidate file.js

The only thing to note about running from the command line: if the validation succeeds, you won’t get much in the way of confirmation. Which can be painful if you are processing a whole directory. You only get useful feedback in the default mode on error.

However, if you don’t mind reading a little XML:

esvalidate lib/*.js --format=junit

Prints junit XML which at least you can visually parse to see which files were validated.

Where would I use this where I might not use JsHint? As a pre-commit hook to screen my checkins. Instead of going through a check-in, building everything, then running JSHint just to hear that something is not up to spec, I can add a little script that will do a quick sanity check of my JS before I go to commit anything to git.

If you’ve never created a pre-commit hook before, it’s pretty easy. Two lines in bash will give you a pre-commit file:

touch .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

This is windows version of the code for the pre-commit hook:

files=$(git diff-index --name-only HEAD | grep -l '\.js$')
for file in $files; do
esvalidate $file
if [ $? -eq 1 ]; then
echo "Syntax error: $file"
exit 1

To make this work on Linux, just remove the remove the #!/bin/sh line.

For more information about Esprima, check out this article by the author.

Derby.js – The Ready() Function, and Adding Client-Side Scripts to your App

I’ve found a neat feature of derby dealing with the ready() function.

I’ve been creating a derby app, and in my application I need to load up a client-side calendar. With a standard HTML web page this is straightforward thing to do. On the page you wanted the calendar, you would include the client js for the calendar, some code to load it, and that would be that.

Derby introduced some complexity to this relatively simple task.

On my first attempt, I put my scripts in the section of the page that I needed the calendar on. I added a script to load the calendar as well. When I went to the url of the page, it loaded immediately. Success! (I thought).

Then I clicked a link away from my calendar, and then clicked back. No calendar.

What happened? When I loaded the link originally, the page was rendered from the server. The second time, the page was rendered client side. Something wasn’t working with loading the calendar on the client-side render.

You need a place to put your code that guarantees that it will load on the client-side. The app.ready() function is designed to handle this scenario.

What is the purpose of the app.ready() function? From the derby documentation:

Code that responds to user events and model events should be placed within the app.ready() callback. This provides the model object for the client and makes sure that the code is only executed on the client.

This function is called as soon as the Derby app is loaded on the client. Note that any code within this callback is only executed on the client and not on the server.

I’ve bolded the part I think is particularly important. This code is run as soon as the client is loaded. Which means if you have more than a single-page app, using app.ready() to load a feature might not work out.

So what to do? An undocumented feature of Derby – app.on().

What does it do? It allows you to load code AFTER a specific page has loaded. Which is exactly what I’m looking for.

So here’s what I ended up writing in my app.ready():

  app.on('render:calendar', function(ctx) {
    logger.log("rendering calendar client-side...");
    new Timeline("timeline", new Date());

In this example this code will run after rendering the calendar view. On the Calendar page, there is a script block which loads the Timeline function.

After writing this code, I tried my page again. Still no luck. I wasn’t getting the calendar to load on both the client and server load.

On a lark, I moved the block containing my Timeline javascript to my index view, and tried again. Success.

Which makes sense. If you are rendering pages via the client side load, additional resources aren’t going to be loaded. So by putting my script into the index view, it’s unfortunately loaded for all my pages, but at least it’s available for both the client and server side rendering of my cool control.

Cracking the Coding Interview – The Tower of Hanoi and Poor Editing

I just finished the Stack section of Cracking the Coding Interview and came across an old puzzle – The Tower of Hanoi.

I struggled with solving this problem. I wrote this elaborate, strange algorithm to try to solve it (which should have been a dead give-away that I had it wrong). Ironically enough, hidden in the 20-30 lines of code I wrote were the three lines of code I needed to solve the problem.

Anyways, after beating my head in trying to solve this, I ended up going to the back of the book and looking up the solution.

And found this pile of shit psuedocode. I’ve shortened the comments, but the content is the same.

moveDisks(int n, Tower origin, Tower destination, Tower buffer) {

   if (n <= 0) return;

   //Move top n - 1 disks from 1 to 2
   moveDisks(n-1, tower 1, tower 2, tower 3);

   //Move top from 1 to 3
   moveTop(tower 1, tower 3);

   //Move top n - 1 disks from 2 to 3
   moveDisks(n-1, tower 2, tower 3, tower 1);

In this tiny amount of code, in over five revisions to her book, the author has managed to miss two errors.

  1. In the first line, Variables origin, destination, and buffer are declared, but then tower 1, tower 2, and tower 3 are used. Which is which?
  2. In line 5, the comment says “Move top n-1 disks”. Then, in lines 8-9, the author indicates that you move the top. Since you’ve already moved all the items in the stack but one, the bottom element, that line should read “move bottom”.

Maybe these aren’t huge issues, but since I was pretty frustrated with this problem, having to correct the solution didn’t help my frustration.

The correct code:

moveDisks(int n, Tower origin, Tower destination, Tower buffer) {

   if (n <= 0) return;

   //Move top n - 1 disks from origin to buffer
   moveDisks(n-1, origin, buffer, destination);

   //Move nth disk (the bottom disk) from origin to destination
   moveBottom(origin , destination);

   //Move top n - 1 disks from buffer to destination
   moveDisks(n-1, buffer, destination, origin);

I hope this helps somebody else who’s working on this problem.