todos

Let’s Build A Todo App With BackboneJS And CoffeeScript

This tutorial will teach you how to put together a Todo app using CoffeeScript and BackboneJS. You can find the entire code for this tutorial on the Github repository.

Here’s What We’ll Build

The todo app is inspired by TodoMVC, except that we’re using Backbone.js alongside CoffeeScript as our stack, and we’ll style the app differently.

todos

It should allow a user to specify items to be done later, and to check off those items as they complete them. In addition, a user can filter items by status so they can see just the completed items or the non-completed ones. Here’s another screenshot of the application.

the app

Funny story about CoffeeScript and BackboneJS, they have something in common.

Quick question: What do they have in common. This is a really geeky-culture test, so don’t feel bad if you could only name JavaScript as being the unifying theme.

No, beyond that, the core unifier is that both of these popular open source tools were developed by the insanely prolific and insightful Jeremy Ashkenas, who, along with TJ and a handful others, has gotta be one of the best things to happen to the JavaScript community.

So if you’ve coded for any reasonable time with Backbone or Coffeescript, you can’t help but notice the same examples of delightful craftsmanship and detail that Jeremy has brought to both projects. He has worked on UnderscoreJS and other things, and I’m an avid user of Underscore as well. So if you haven’t come across that great library before, you should certainly check it out. With little doubt, using Underscore, and reading the source, will make you a much better JavaScript developer.

Getting Backbone.js And Coffeescript

First order of business, download Backbone.js here. You’ll want to follow the instructions as far as downloading Backbone’s dependencies as well, which should be just Underscore and jQuery. This tutorial is based on version 1.3.3 of Backbone.js, but should work with newer versions. Given the stability of Backbone, even older versions of the library will work with this example code with minimal modifications. Another great benefit of working with Backbone.

For CoffeeScript, the recommended way is to install the command line compiler and REPL via npm. Install it using the installation instructions found here.

Now create a new directory called “BackboneTodos” anywhere on your computer. Inside this directory, create a new directory called js, which is where our JavaScript and CoffeeScript files are going to live.

Next, inside your js directory, create a new directory called lib where you will place all of Backbone.js and its dependencies, excluding CoffeeScript which has its own usage and installation as detailed above.

Assuming you have CoffeeScript, Backbone.js and dependencies installed, there remains one more dependency. If you scan my source code, you’ll see I’m using the Backbone.LocalStorage plugin to store the Todos. You should grab a copy of this file and save it, again, in your lib folder.

So currently, your folder structure should look as follows

[pastacode lang=”bash” manual=”BackboneTodos%2Fjs%2Flib” message=”” highlight=”” provider=”manual”/]

Note, there is nothing special about the “lib” folder, it’s just an arbitrary name for a folder where we are holding our application’s libraries.

Say Hello World

Now let’s create our home page. Create a new file inside your BackboneTodos directory, which is the root folder of the app. Call the new file, predictably, index.html

Inside index.html, let’s create the basic HTML template that says “Hello World” so we know we’re in business. Here’s the code you should put in index.html

[pastacode lang=”markup” manual=”%3C!DOCTYPE%20html%3E%0A%3Chtml%20lang%3D%22en%22%3E%0A%20%20%3Chead%3E%0A%20%20%20%20%3Cmeta%20charset%3D%22utf-8%22%3E%0A%20%20%20%20%3Cmeta%20http-equiv%3D%22X-UA-Compatible%22%20content%3D%22IE%3Dedge%22%3E%0A%20%20%20%20%3Cmeta%20name%3D%22viewport%22%20content%3D%22width%3Ddevice-width%2C%20initial-scale%3D1%22%3E%0A%20%20%20%20%3Ctitle%3EZeyron%20Task%20Manager%3C%2Ftitle%3E%0A%20%20%20%20%3Clink%20rel%3D%22stylesheet%22%20href%3D%22css%2Findex.css%22%3E%0A%20%20%20%20%3Clink%20rel%3D%22stylesheet%22%20href%3D%22css%2Fblingstyles.css%22%3E%0A%0A%20%20%20%20%3C!–%20HTML5%20Shim%20and%20Respond.js%20IE8%20support%20of%20HTML5%20elements%20and%20media%20queries%20–%3E%0A%20%20%20%20%3C!–%20WARNING%3A%20Respond.js%20doesn’t%20work%20if%20you%20view%20the%20page%20via%20file%3A%2F%2F%20–%3E%0A%20%20%20%20%3C!–%5Bif%20lt%20IE%209%5D%3E%0A%20%20%20%20%20%20%3Cscript%20src%3D%22https%3A%2F%2Foss.maxcdn.com%2Flibs%2Fhtml5shiv%2F3.7.2%2Fhtml5shiv.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%20%20%3Cscript%20src%3D%22https%3A%2F%2Foss.maxcdn.com%2Flibs%2Frespond.js%2F1.4.2%2Frespond.min.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%3C!%5Bendif%5D–%3E%0A%20%20%3C%2Fhead%3E%0A%20%20%3Cbody%3E%0A%20%20%20%20%20%3Ch1%3EHello%20World!%3C%2Fh1%3E%0A%20%20%3C%2Fbody%3E” message=”” highlight=”” provider=”manual”/]

You’ll notice that I’m including some shims and meta tags. Copy everything in. This is just a standard boilerplate that sets up the page to support different browsers.

Now open index.html in your web browser and you should see the text “Hello World”.

backbone.js

Say It With Style

If you look carefully at the above code, you’ll notice I’m including two style sheets. The first has some basic styles, and the second really brings on the style, so you will want to grab one or both stylesheets in order to get your UI looking neat. Place them in the appropriately named css folder, so now your file structure nests a js folder and a css folder under the BackboneTodos parent folder.

In addition to the CSS files, now let’s load Backbone.js and all its dependencies on the page. Before the closing </body> tag in your index.html, now add some script tags to load these javascript libraries, as follows.

[pastacode lang=”markup” manual=”%3Cscript%20src%3D%22js%2Flib%2Fjquery.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%3Cscript%20src%3D%22js%2Flib%2Funderscore.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%3Cscript%20src%3D%22js%2Flib%2Fbackbone.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%3Cscript%20src%3D%22js%2Flib%2Fbackbone.localStorage.js%22%3E%3C%2Fscript%3E” message=”” highlight=”” provider=”manual”/]

We still don’t have the actual todos shown on the page, so let’s add some HTML that will consist of a section where our Todos will be listed. We will also remove the line that reads <h1>Hello World!</h1>, we don’t need it now. Instead, we will replace it with the following HTML.

[pastacode lang=”markup” manual=”%3Csection%20class%3D%22responsive%22%3E%0A%20%20%20%20%20%20%3Ch1%3EBackboneJS-CoffeeScript%20Todos%3C%2Fh1%3E%0A%20%20%20%20%20%20%3Csection%20id%3D%22todoapp%22%3E%0A%20%20%20%20%20%20%20%20%3Cheader%3E%0A%0A%20%20%20%20%20%20%20%20%3C%2Fheader%3E%0A%20%20%20%20%20%20%20%20%3Cinput%20id%3D%22new-todo%22%20placeholder%3D%22What%20needs%20to%20be%20done%3F%22%3E%0A%20%20%20%20%20%20%20%20%3Csection%20id%3D%22main%22%3E%0A%20%20%20%20%20%20%20%20%20%20%3Cinput%20type%3D%22checkbox%22%20id%3D%22toggle-all%22%20hidden%3E%0A%20%20%20%20%20%20%20%20%20%20%3Clabel%20for%3D%22toggle-all%22%3EMark%20all%20as%20complete%3C%2Flabel%3E%0A%20%20%20%20%20%20%20%20%20%20%3Cul%20id%3D%22todo-list%22%3E%0A%0A%20%20%20%20%20%20%20%20%20%20%3C%2Ful%3E%0A%20%20%20%20%20%20%20%20%3C%2Fsection%3E%0A%20%20%20%20%20%20%20%20%3Cfooter%20id%3D%22footer%22%3E%3C%2Ffooter%3E%0A%20%20%20%20%20%20%3C%2Fsection%3E%0A%20%20%20%20%20%20%3Cdiv%20id%3D%22info%22%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EDouble-click%20to%20edit%20a%20todo%3C%2Fp%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EWritten%20by%20%3Ca%20href%3D%22http%3A%2F%2Ftowersofzeyron.com%22%3ETendai%20Mutunhire%3C%2Fa%3E%3C%2Fp%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EA%20production%20of%20%3Ca%20href%3D%22http%3A%2F%2Ftowersofzeyron.com%22%3ETowersOfZeyron%3C%2Fa%3E%3C%2Fp%3E%0A%20%20%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3C%2Fsection%3E” message=”” highlight=”” provider=”manual”/]

This is the main section of our app where we are going to display Todos, mark todos as completed, as well as add and remove todos. Once you’ve added the new HTML, when you do a page refresh, this is what you should see.

See also  Talent alone won’t get you the job

coffeescript

If your app doesn’t look half as good, make sure you have downloaded the two style files I linked to in the repository above “index.css” and “blingstyles.css”. Once you’ve downloaded them, remember to include them in the head section of index.html using stylesheet tags.

See that giant input field that says “What needs to be done?”. Now you should try to enter some text in there for a todo. Press enter when you are done and see what happens.

Wait, nothing happened! That’s right, for that to happen we need the help of Backbone.js, so let’s actually create some code now that will add logic to save whatever text we type as a new todo item.

Backbone Collections, Models And Views

This is the part where you learn enough Backbone.js to get your hands dirty. Backbone is built around the MVC pattern, heavily inspired by Ruby on Rails and similar frameworks. It brings MVC to the browser in a very elegant way.

Take our Todo app for instance. Backbone has the notion of a Collection, which is a special Backbone class that will allow us to store all our todos in one grouping that we can update or filter to retrieve or set new information.

Individual Todos will be represented by a Model, which is a mirror of what our data looks like on the server or in a database. Here, we are using local storage instead of a database, but frequently, you will have a database on the server that you work with.

For each Model, there will also be a view, which presents the details of the Model to the user. The View does not change the Model directly. Rather the view fires off events, which are then responsible for changing the state of the model. The view also listens for changes to the model and the collection of models. When these change, then the view changes.

Now, let us create our Todo model, which will hold details about an individual Todo item. Think about what attributes a Todo needs to have:

It obviously needs a title, telling us what is to be done, as well as a status, whether the Todo has been completed or has not yet been completed. We could add more attributes to get fancy, but let’s go with these basic attributes for now.

Create a new file at the path BackboneTodos/js/models/todo.coffee containing the following definition of the Todo model.

[pastacode lang=”coffeescript” manual=”%0A%40Todo%20%3D%20Backbone.Model.extend%0A%20%20defaults%3A%0A%20%20%20%20title%3A%20”%0A%20%20%20%20completed%3A%20false%0A%0A%20%20toggle%3A%20-%3E%0A%20%20%20%20this.save%0A%20%20%20%20%20%20%20%20completed%3A%20!this.get%20’completed'” message=”” highlight=”” provider=”manual”/]

That’s CoffeeScript that will be compiled into JavaScript, and defines Todo as a Backbone model with a title and “completed” status. There’s also a function toggle defined, so we can call it whenever we want to change the completed status of a given todo.

Now to compile your CoffeeScript into JavaScript, we’ll use that CoffeeScript compiler we installed earlier.

In a terminal window, cd into your project’s root folder, and run the following:

[pastacode lang=”bash” manual=”coffee%20-wc%20.” message=”” highlight=”” provider=”manual”/]

This runs CoffeeScript with the compile and watch flags, which tells CoffeeScript to compile any CoffeeScript files in the current directory, and watch for any changes. Do not forget the dot (.) at the end of that command, it stands for the current directory. Leave that terminal command running, and look inside the BackboneTodos/js/models folder, and you should see a new file, todo.js, has appeared. That’s our todo.coffee compiled into JavaScript. 

Now let’s define a Collection that will hold Todo models. Create a new file at BackboneTodos/js/collections/todos.coffee. Inside that file, include the following definition of a Collection named TodoList, and an instantiation, finally, of such a collection.

[pastacode lang=”coffeescript” manual=”%0A%23%20Todo%20Collection%0A%40TodoList%20%3D%20Backbone.Collection.extend%0A%20%20model%3A%20Todo%0A%20%20localStorage%3A%20new%20Backbone.LocalStorage%20’todos-backbone’%0A%0A%20%20completed%3A%20-%3E%0A%20%20%20%20this.filter%20(todo)-%3E%0A%20%20%20%20%20%20todo.get%20’completed’%0A%0A%20%20remaining%3A%20-%3E%0A%20%20%20%20this.without.apply%20this%2C%20this.completed()%0A%0A%20%20nextOrder%3A%20-%3E%0A%20%20%20%20if%20!this.length%0A%20%20%20%20%20%20return%201%0A%20%20%20%20this.last().get(‘order’)%20%2B%201%0A%0A%20%20%23%20Todos%20are%20sorted%20by%20their%20original%20insertion%20order%0A%20%20comparator%3A%20(todo)-%3E%0A%20%20%20%20todo.get%20’order’%0A%0A%23%20create%20a%20global%20collection%20of%20Todos%0A%40Todos%20%3D%20new%20TodoList()” message=”” highlight=”” provider=”manual”/]

Likewise, CoffeeScript, that’s running with the coffee -wc . invocation, will compile this new file into JavaScript on the fly. Inside the new CoffeeScript file, we are specifying the Todo model defined earlier as the model we want this new TodoList collection to hold. In other words, it will aggregate a bunch of Todo models.

Further, we are defining a completed method to filter for Todos that are complete, as well as a few other methods to allow us to query and update the list of Todos.

The next major piece we will want now is to include a router, which will allow us to filter and view specific subsets of our Todo collection. There are three filters we want to be able to see: all (shows all todos), completed (only shows completed todos) and active (only shows active todos).

So let’s create a new router file at BackboneTodos/js/router/router.coffee with the following

[pastacode lang=”coffeescript” manual=”WorkSpace%20%3D%20Backbone.Router.extend%0A%20%20routes%3A%0A%20%20%20%20%22*filter%22%3A%20%22setFilter%22%0A%0A%20%20setFilter%3A%20(param)-%3E%0A%20%20%20%20console.log%20%22inside%20router%20filter%22%0A%20%20%20%20console.log%20param%0A%20%20%20%20if%20param%0A%20%20%20%20%20%20param%20%3D%20param.trim()%0A%20%20%20%20%40TodoFilter%20%3D%20param%0A%20%20%20%20Todos.trigger%20%22filter%22%0A%0A%23%20%40TodoFilter%20%3D%20%22completed%22%0A%40TodoRouter%20%3D%20new%20WorkSpace()%0ABackbone.history.start()%0A” message=”” highlight=”” provider=”manual”/]

We have a Collection, we have a Model, but where is the View?

Before we get to the View part of MVC so we can see our app in all its bling, let’s set up our index.html to utilize the new code we just added, as well as pull in some as-yet undefined scripts that will set up the View.

Back in index.html, under our script tags we defined earlier, add the following script tags, before the closing </body> tag.

See also  What Is Ray Dalio'S Net Worth In 2020

[pastacode lang=”markup” manual=”%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20%20%20%20%20%20window.TodoFilter%20%3D%20%7B%7D%0A%3C%2Fscript%3E%0A%3Cscript%20src%3D%22js%2Fmodels%2Ftodo.js%22%3E%3C%2Fscript%3E%0A%20%20%20%20%3Cscript%20src%3D%22js%2Fcollections%2Ftodos.js%22%3E%3C%2Fscript%3E%0A%3Cscript%20src%3D%22js%2Fviews%2Ftodos.js%22%3E%3C%2Fscript%3E%3Cscript%20src%3D%22js%2Fviews%2Fapp.js%22%3E%3C%2Fscript%3E%0A%3Cscript%20src%3D%22js%2Frouter%2Frouter.js%22%3E%3C%2Fscript%3E%0A%3Cscript%20src%3D%22js%2Fapp.js%22%3E%3C%2Fscript%3E%0A” message=”” highlight=”” provider=”manual”/]

We’re pulling in the scripts we wrote earlier. You’ll also notice we’re pulling in 3 scripts that are currently missing.

In order to use these scripts, let’s first define a couple of templates, which Backbone will use to render new Todos and filter todos.

The first template defines the view for a new todo, which we will append to the main document when a user enters text for a todo. Add the following code to index.html, inside the body but before the first of the script tags.

Including the last part of the section defined earlier, it looks like the following:

[pastacode lang=”markup” manual=”%3Cdiv%20id%3D%22info%22%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EDouble-click%20to%20edit%20a%20todo%3C%2Fp%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EWritten%20by%20%3Ca%20href%3D%22http%3A%2F%2Ftowersofzeyron.com%22%3ETendai%20Mutunhire%3C%2Fa%3E%3C%2Fp%3E%0A%20%20%20%20%20%20%20%20%3Cp%3EA%20production%20of%20%3Ca%20href%3D%22http%3A%2F%2Ftowersofzeyron.com%22%3ETowersOfZeyron%3C%2Fa%3E%3C%2Fp%3E%0A%20%20%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3C%2Fsection%3E%0A%0A%0A%20%20%20%20%3Cscript%20type%3D%22text%2Ftemplate%22%20id%3D%22item-template%22%3E%0A%20%20%20%20%20%20%3Cdiv%20class%3D%22view%22%3E%0A%20%20%20%20%20%20%20%20%3Cinput%20class%3D%22toggle%22%20type%3D%22checkbox%22%20%3C%25%3D%20completed%20%3F%20’checked’%20%3A%20”%25%3E%3E%0A%20%20%20%20%20%20%20%20%3Clabel%20class%3D%22todo-label%22%3E%3Cspan%3E%3C%25%3D%20title%20%25%3E%3C%2Fspan%3E%3C%2Flabel%3E%0A%20%20%20%20%20%20%20%20%3Cbutton%20class%3D%22destroy%22%3Ex%3C%2Fbutton%3E%0A%20%20%20%20%20%20%20%20%3Cinput%20class%3D%22edit%22%20value%3D%22%3C%25%3D%20title%20%25%3E%22%20style%3D%22border-top%3A1px%20solid%22%20hidden%3D%22hidden%22%3E%0A%20%20%20%20%20%20%3C%2Fdiv%3E%0A%20%20%20%20%3C%2Fscript%3E” message=”” highlight=”” provider=”manual”/]

The template is enclosed in a script tag, but we are giving it a type of “text/template” so it does not show immediately on the page. Rather, when the user clicks enter after typing a Todo, we will then use Backbone to add a li list item, containing the HTML in the defined template. As you can see, we will render the title of the Todo, as well as a checkbox showing if it’s complete or not, and a button that allows us to destroy the Todo.

We can now write the Backbone code that constructs the View for an individual todo, using the template defined above, and listens for events such as a user hitting the “enter” key. Create a new file at BackboneTodos/js/views/todos.coffee with contents as below.

[pastacode lang=”coffeescript” manual=”%60var%20app%20%3D%20app%20%7C%7C%20%7B%7D%60%0A%0A%0A%40TodoView%20%3D%20Backbone.View.extend%0A%20%20tagName%3A%20%22li%22%0A%20%20template%3A%20_.template(%20%24(%22%23item-template%22).html()%20)%0A%20%20events%3A%0A%20%20%20%20%22click%20.toggle%22%3A%20%22toggleCompleted%22%0A%20%20%20%20%22dblclick%20label%22%3A%20%22edit%22%0A%20%20%20%20%22click%20.destroy%22%3A%20%22clear%22%0A%20%20%20%20%22keypress%20.edit%22%3A%20%22updateOnEnter%22%0A%20%20%20%20%22blur%20.edit%22%3A%20%22close%22%0A%0A%20%20initialize%3A%20-%3E%0A%20%20%20%20this.listenTo%20this.model%2C%20%22change%22%2C%20this.render%0A%20%20%20%20this.listenTo%20this.model%2C%20%22destroy%22%2C%20this.remove%0A%20%20%20%20this.listenTo%20this.model%2C%20%22visible%22%2C%20this.toggleVisible%0A%0A%20%20render%3A%20-%3E%0A%20%20%20%20console.log%20%22rendering%20todo%22%0A%20%20%20%20this.%24el.html%20this.template(this.model.attributes)%0A%20%20%20%20this.%24el.toggleClass(%22completed%22%2C%20this.model.get(%22completed%22))%0A%20%20%20%20this.toggleVisible()%0A%20%20%20%20this.%24input%20%3D%20this.%24(%22.edit%22)%0A%20%20%20%20this%0A%0A%20%20toggleVisible%3A%20-%3E%0A%20%20%20%20this.%24el.toggleClass(%22hidden%22%2C%20this.isHidden())%0A%0A%20%20%23%20determines%20if%20item%20should%20be%20hidden%0A%20%20isHidden%3A%20-%3E%0A%20%20%20%20isCompleted%20%3D%20this.model.get%20%22completed%22%0A%20%20%20%20return((!isCompleted%20%26%26%20TodoFilter%20%3D%3D%20%22completed%22)%20%7C%7C%20(isCompleted%20%26%26%20TodoFilter%20%3D%3D%20%22active%22)%20)%0A%0A%20%20%23%20toggle%20the%20%22completed%22%20state%20of%20the%20model%2C%20the%20change%20is%20immediately%20persisted%0A%20%20toggleCompleted%3A%20-%3E%0A%20%20%20%20this.model.toggle()%0A%0A%20%20edit%3A%20-%3E%0A%20%20%20%20console.log%20%22now%20editing%22%0A%20%20%20%20this.%24el.addClass%20%22editing%22%0A%20%20%20%20this.%24input.removeAttr(%22hidden%22)%0A%20%20%20%20this.%24input.focus()%0A%0A%20%20close%3A%20-%3E%0A%20%20%20%20value%20%3D%20this.%24input.val().trim()%0A%0A%20%20%20%20if%20value%0A%20%20%20%20%20%20this.model.save(%7Btitle%3A%20value%7D)%0A%20%20%20%20else%0A%20%20%20%20%20%20this.clear()%0A%0A%20%20%20%20this.%24el.removeClass%20%22editing%22%0A%0A%20%20updateOnEnter%3A%20(e)-%3E%0A%20%20%20%20if%20e.which%20%3D%3D%20ENTER_KEY%0A%20%20%20%20%20%20this.close()%0A%0A%20%20clear%3A%20-%3E%0A%20%20%20%20this.model.destroy()%0A” message=”” highlight=”” provider=”manual”/]

Here’s the documentation about Backbone Views which you should study a bit to really see the elegance of what the above view code achieves, courtesy of Backbone. Now events and user interaction are handled for us thanks to the above.

We have a View defined for Todos, but we need to actually make an instance of the view to have all the functionality on the page. We will therefore create a main view of the application, which is what will create the individual Todo Views when a new Todo is entered in the input for new Todos. This view will also list all the existing Todo items in a list. So now create a new file at BackboneTodos/js/views/app.coffee which contains the definition of the main View.

[pastacode lang=”coffeescript” manual=”%60var%20app%20%3D%20app%20%7C%7C%20%7B%7D%60%0A%23%20%40TodoFilter%20%3D%20%22completed%22%0A%0A%40AppView%20%3D%20Backbone.View.extend%0A%20%20el%3A%20%22%23todoapp%22%0A%20%20statsTemplate%3A%20_.template%20%24(%22%23stats-template%22).html()%0A%0A%20%20%23%20delegated%20events%20for%20creating%20new%20items%20and%20clearing%20completed%20ones%0A%20%20events%3A%0A%20%20%20%20%22keypress%20%23new-todo%22%3A%20%22createOnEnter%22%0A%20%20%20%20%22click%20%23clear-completed%22%3A%20%22clearCompleted%22%0A%20%20%20%20%22click%20%23toggle-all%22%3A%20%22toggleAllComplete%22%0A%0A%20%20initialize%20%3A%20-%3E%0A%20%20%20%20this.allCheckbox%20%3D%20this.%24(%22%23toggle-all%22)%5B0%5D%0A%20%20%20%20this.%24input%20%3D%20this.%24(%22%23new-todo%22)%0A%20%20%20%20this.%24footer%20%3D%20this.%24(%22%23footer%22)%0A%20%20%20%20this.%24main%20%3D%20this.%24(%22%23main%22)%0A%0A%20%20%20%20this.listenTo%20Todos%2C%20%22add%22%2C%20this.addOne%0A%20%20%20%20this.listenTo%20Todos%2C%20%22reset%22%2C%20this.addAll%0A%20%20%20%20this.listenTo%20Todos%2C%20%22change%3Acompleted%22%2C%20this.filterOne%0A%20%20%20%20this.listenTo%20Todos%2C%20%22filter%22%2C%20this.filterAll%0A%20%20%20%20this.listenTo%20Todos%2C%20%22all%22%2C%20this.render%0A%0A%20%20%20%20%23%20get%20the%20Todos%20from%20the%20store%0A%20%20%20%20Todos.fetch()%0A%0A%20%20%23%20New%2C%20re-rendering%20the%20app%20just%20means%20refreshing%20the%20statistics%0A%20%20%23%20The%20rest%20of%20the%20app%20doesn’t%20change%0A%20%20render%3A%20-%3E%0A%20%20%20%20completed%20%3D%20Todos.completed().length%0A%20%20%20%20remaining%20%3D%20Todos.remaining().length%0A%0A%20%20%20%20if%20Todos.length%0A%20%20%20%20%20%20this.%24main.show()%0A%20%20%20%20%20%20this.%24footer.show()%0A%20%20%20%20%20%20this.%24footer.html%20this.statsTemplate%0A%20%20%20%20%20%20%20%20completed%3A%20completed%0A%20%20%20%20%20%20%20%20remaining%3A%20remaining%0A%0A%20%20%20%20%20%20this.%24(%22%23filters%20li%20a%22)%0A%20%20%20%20%20%20%20%20.removeClass%20%22selected%22%0A%20%20%20%20%20%20%20%20.filter(‘%5Bhref%3D%22%23%2F’%20%2B%20(%20TodoFilter%20%7C%7C%20”%20)%20%2B%20%20’%22%5D’)%0A%20%20%20%20%20%20%20%20.addClass%20%22selected%22%0A%20%20%20%20else%0A%20%20%20%20%20%20this.%24main.hide()%0A%20%20%20%20%20%20this.%24footer.hide()%0A%20%20%20%20this.allCheckbox.checked%20%3D%20!remaining%0A%0A%20%20addOne%3A%20(todo)-%3E%0A%20%20%20%20view%20%3D%20new%20TodoView(%7Bmodel%3A%20todo%7D)%0A%20%20%20%20console.log%20%22adding%20one%20todo%22%0A%20%20%20%20this.%24(%22%23todo-list%22).append%20view.render().el%0A%0A%20%20addAll%3A%20-%3E%0A%20%20%20%20this.%24(%22%23todo-list%22).html%20%22%22%0A%20%20%20%20console.log%20%22adding%20all%20todos%22%0A%20%20%20%20Todos.each%20this.addOne%2C%20this%0A%0A%20%20filterOne%3A%20(todo)-%3E%0A%20%20%20%20todo.trigger%20%22visible%22%0A%0A%20%20filterAll%3A%20-%3E%0A%20%20%20%20Todos.each%20this.filterOne%2C%20this%0A%0A%20%20%23%20general%20attributes%20for%20a%20new%20Todo%20item%0A%20%20newAttributes%3A%20-%3E%0A%20%20%20%20title%3A%20this.%24input.val().trim()%0A%20%20%20%20order%3A%20Todos.nextOrder()%0A%20%20%20%20completed%3A%20false%0A%0A%20%20%23%20when%20you%20hit%20return%20in%20the%20todo%20input%20field%2C%20create%20a%20new%20Todo%20model%0A%20%20%23%20persisting%20it%20to%20localStorage%0A%20%20createOnEnter%3A%20(event)-%3E%0A%20%20%20%20if%20event.which%20!%3D%20ENTER_KEY%20%7C%7C%20!this.%24input.val().trim()%0A%20%20%20%20%20%20return%0A%20%20%20%20console.log%20%22creating%20a%20new%20Todo%22%20%0A%20%20%20%20Todos.create%20this.newAttributes()%0A%20%20%20%20this.%24input.val%20%22%22%0A%0A%20%20clearCompleted%3A%20-%3E%0A%20%20%20%20_.invoke%20Todos.completed()%2C%20%22destroy%22%0A%20%20%20%20return%20false%0A%0A%20%20toggleAllComplete%3A%20-%3E%0A%20%20%20%20completed%20%3D%20this.allCheckbox.checked%0A%0A%20%20%20%20Todos.each%20(todo)-%3E%0A%20%20%20%20%20%20todo.save%20%7B%22completed%22%3A%20completed%7D%0A” message=”” highlight=”” provider=”manual”/]

In the above code, we are listening for events like keypress inside the input for a new Todo. Whenever there is a keypress, we delegate to the createOnEnter function. This is where we check to see if the key the user has pressed was the Enter key. If it is, we then take all the text the user has entered in the input, and create a new instance of the Todo model and save it. That causes a change to the TodoList collection, and in the newly defined view, we are also listening for changes to the collection, among other things. When a new Todo is added to the collection, we then create a new instance of the Todo View for individual Todo items, and append it to the todo list in our index.html identified by the code this.$(“#todo-list”) .

All that remains now is to instantiate our AppView defined above, which will set up the rest for us. So now create a new file at BackboneTodos/js/app.coffee, which will simply create a new AppView and allow us to fully interact with the app:

[pastacode lang=”coffeescript” manual=”%60%0Avar%20app%20%3D%20app%20%7C%7C%20%7B%7D%3B%0AENTER_KEY%20%3D%2013%60%0AjQuery(document).ready%20-%3E%0A%20%20ENTER_KEY%20%3D%2013%0A%20%20new%20AppView()” message=”” highlight=”” provider=”manual”/]

Now you should be able to enter a new Todo, as well as double click to edit an existing Todo. You can also delete a Todo by clicking on the button to the right of each Todo. But what about if we want to see only Completed or only Active Todos?

We already defined filter functions for this in our router file and our main view and the collection itself. So now, all that remains is to add a template at the bottom of the page with links pointing to routes that trigger the filters for completed or active Todos.

Back in index.html, below the template with an id of “item-template”, create a new template for the footer, with the following code

[pastacode lang=”markup” manual=”%3Cscript%20type%3D%22text%2Ftemplate%22%20id%3D%22stats-template%22%3E%0A%20%20%20%20%20%20%3Cspan%20id%3D%22todo-count%22%3E%3Cstrong%3E%3C%25%3D%20remaining%20%25%3E%3C%2Fstrong%3E%20%3C%25%3D%20remaining%20%3D%3D%3D%201%20%3F%20’item’%20%3A%20’items’%20%25%3E%20left%3C%2Fspan%3E%0A%20%20%20%20%20%20%3Cul%20id%3D%22filters%22%3E%0A%20%20%20%20%20%20%20%20%3Cli%3E%0A%20%20%20%20%20%20%20%20%20%20%3Ca%20class%3D%22selected%22%20href%3D%22%23%2F%22%3EAll%3C%2Fa%3E%0A%20%20%20%20%20%20%20%20%3C%2Fli%3E%0A%20%20%20%20%20%20%20%20%3Cli%3E%0A%20%20%20%20%20%20%20%20%20%20%3Ca%20href%3D%22%23%2Factive%22%3EActive%3C%2Fa%3E%0A%20%20%20%20%20%20%20%20%3C%2Fli%3E%0A%20%20%20%20%20%20%20%20%3Cli%3E%0A%20%20%20%20%20%20%20%20%20%20%3Ca%20href%3D%22%23%2Fcompleted%22%3ECompleted%3C%2Fa%3E%0A%20%20%20%20%20%20%20%20%3C%2Fli%3E%0A%20%20%20%20%20%20%3C%2Ful%3E%0A%20%20%20%20%20%20%3C%25%20if%20(completed)%20%7B%20%25%3E%0A%20%20%20%20%20%20%3Cbutton%20id%3D%22clear-completed%22%3EClear%20completed%20(%3C%25%3D%20completed%20%25%3E)%3C%2Fbutton%3E%0A%20%20%20%20%20%20%3C%25%20%7D%20%25%3E%0A%20%20%20%20%3C%2Fscript%3E” message=”” highlight=”” provider=”manual”/]

Now trying clicking on the links for Active or Completed or All todos. You should be able to see the route change, and to see only the todos that match the filter of “active” or “completed”. Here is the code repository on Github again if you need it.

That’s how we create a Todo app with Backbone.js and CoffeeScript! Backbone is an exquisite library, useful for many different types of apps, and scales insanely well since it’s such a lightweight lib. CoffeeScript will add elegance and maintainability to your JavaScript code so the whole set up is a great leap ahead for making JavaScript apps. Have fun!

 

I help solopreneurs get MORE PROFITABLE in WAY LESS TIME, grow and scale their one man businesses into time independent 7-8 figure machines that make money even when you’re asleep. Learn how in my Renegade Solopreneur Profits Bootcamp.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended
For web developers and designers out there, in an effort…