Month: October 2011

There are certainly plenty of articles, examples, etc… around creating the ‘Todos’ sample. To learn more about different frameworks and a more complete example, check out Addy Osmani‘s examples here: http://addyosmani.github.com/todomvc/ This is a fantastic resource to learn about different available frameworks.

Most of these examples tend to use the localStorage. Not that it’s a big deal, but I wanted to put together something very very simple that showed some connections between using Backbone.js to make calls to a backend server. In this case, I have decided to use asp.net mvc.

The example uses IISExpress to be hosted. To reduce some of the friction, there is no database, just a static List object on the server. I am not handling edits in this simple example – just a GET call to show todos and POST call to add a new todo.

First, this is not a ‘how to use backbone’ nor a ‘how to use asp.net mvc’ – I’d probably fail you on both subject matters! The goal here is to highlight the aspects of backbone that help in making the connection to the backend server. Backbone is providing an abstraction over the ajax calls. You certainly CAN use ajax directly if you want.

So, let’s get started. The ‘todo’ model is quite simple – see todo.js line 5 :

Returns the relative URL where the model’s resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.

This is a basic post regarding namespacing and revealing module pattern. When starting a new JavaScript application it’s important to have a good starting foundation. First let’s show how to use namespacing in JavaScript:

window._ns = window._ns || {};

_ns is attached to the global window object. Alex MacCaw in his book ‘’JavaScript Web Applications’ describes this well:

We’re setting on the window object to ensure that it’s globally accessible.

Also, by using this pattern, it’s easy to see which global variables a script is declaring,

just look through the script for window references

Let’s show this in use, first using what is referred to as the singleton pattern: