Tuesday 22 May 2012

NodeToDos Part 1

Welcome to the first part in a mini series in which we will convert the Backbone.js Todos Example to use a Node.js backend. If you are new to Node.js and need help installing and setting up Node.js, check out my previous post - here.

In the first part of this series I will show you how to create a Node.js project that serves the HTML and JavaScript to the client. The existing Backbone.js code will remain unchanged and the Todos list will still use local HTML storage. In subsequent parts, I will show you how this can be changed to use a MongoDB database.

Getting Started

This first thing we need to do is to create a Node.js project. We will be using Express for this, and it is done by simply typing the following in the command line:

$ express /nodetodo && cd /nodetodo

Now we have to install the dependancy which is simply:

$ npm install -d

The Views

As we are not dealing with any server-side code at the minute, we can leave the majority of the code which Express generates alone. All of our work will be changing the Backbone.js Todos HTML to use the Jade templating engine.

The first step is to copy the images, CSS and JavaScript from the Backbone.js Todos example into the relevant sub-folders within the "public" folder of your Node.js application.

Now that we have done that we can start converting the HTML of the example to Jade. Jade is an extremely elegant and simple templating engine; as I will show, it will reduce the number of lines of code you need from 85 to about 50 in this example. The entire Jade views can be seen below.

There are a few 'gotchas' in Jade, though. The main one is in the use of the break tag. I'm trying to recreate the Backbone.js example line for line, and this example uses line breaks:

Now this does not translate to Jade well, because it will try and create a "Created" tag and does not represent line breaks in the code as HTML line breaks. The work-around this is to use the pipe ("|") which allows us to write free-form text as shown below:

As you can see, we are now adding HTML into our Jade template; this is not ideal but as it happens rarely I don't see this as a huge issue with Jade.

Below are the full contents of the layout.jade and index.jade templates; as you can see the code is clear, clean and concise.

This is just the start in converting the Backbone.js Todos example to use a Node.js backend. In subsequent posts I will be showing you how to use a MongoDB to store the Todos, and how to create a simple API in Node.js for use by Backbone.js.

As always if you want to check out the code for this post and change it, feel free to fork it on GitHub here and submit any pull requests.

No comments:

Post a Comment