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.
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.
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.
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.
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.
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).
Finally, we can create a listening event in jQuery:
In our html, remember to initiate our collection and view.
That’s all. Our app is working. You have your To-do app in your browser. Amazing!