How to Build a To-do app using Backbone.js

In Hack Reactor week 3, we were introduced to Backbone.js. I didn’t fully grasp the concept of Backbone in class, so I would like to practice it and explain my understanding here.

Backbone is an MVC framework that is widely used in Javascript. MVC stands for “Model”, “View”, and “Controller.” The benefit of using MVC is that your code will be cleaner and easier to maintain/expand in the future.

So, first of all, let’s build an HTML page for our To-do app. We need to include jquery, underscore, and backbone library. The app.js is the file we will build for backbone.

Screen Shot 2015-03-13 at 1.57.33 PM

Secondly, we want to build our MVC’s model. I called it ListModel with default id and title. The model will listen to the removeItem event.

Screen Shot 2015-03-13 at 2.00.47 PM

 

The collection is similar to model. Remember to link the model to the one you just created. It also has initialize method which will fire when it is created. Here we have the collection listen to removeItem event and it will remove the item that triggers the event.

Screen Shot 2015-03-13 at 2.02.55 PM

Now we are creating the View part. I made the view as li element in the HTML. It listen to the click event (in the DOM) and trigger the done event, which will remove the model. Here we use underscore’s template for creating each element’s view. If you want to escape your value (safer from attack), then you should change <%= id %> to <%- id %>. The ” – ” can do the escaping trick for you.

Screen Shot 2015-03-13 at 2.05.30 PM

 

 

Here we are creating collection view using ul element. Collection view listen to add and remove event and will update the page (children().detach() and re-render).

 

 

 

Screen Shot 2015-03-13 at 2.09.15 PM

 

Finally, we can create a listening event in jQuery:

Screen Shot 2015-03-13 at 2.11.11 PM

 

In our html, remember to initiate our collection and view.

 

Screen Shot 2015-03-13 at 2.12.10 PM

 

That’s all. Our app is working. You have your To-do app in your browser. Amazing!

Screen Shot 2015-03-13 at 2.13.23 PM

Leave a Reply

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