April 29, 2013
What can Backbone.js do for you?
How to start?
Backbone.js has only one hard dependency, it's small library written by the same developer, Jeremy Ashkenas (he also created CoffeScript) - Underscore.js, it's also very small, few kilobytes minified. It's also recommended to use jQuery (or zepto.js) for DOM manipulation. So, using these 3 libraries - you can get started building awesome Backbone.js app.
Models and Collections
Models in Backbone represent data, let's say I have blog, which contains posts, comments, categories, tags, etc. In this case blog post is a model, category is collection, comment is a model.
Views contain instructions how to render models or collections, once we receive some data from the server - view picks it up, formats it, handles adding new or removing models, etc and passes this information to template (Handlebars, Underscore or any other template engine).
Routers are responsible for navigation. Backbone.js uses HTML5 history API and gracefully degrades in old browsers (you guessed it - Internet Explorer). When building with backbone.js - in most cases you are building one page page application, so there are no page refresh, that's router's job. It directs application and where user wants to go. For example if I'm on home page of my blog and need to view single blog post, I click on read more button, router passes this post ID to view, view requests model attached to this view to fetch content from the server and then renders the content to template.
Let's see how backbone.js works using real example, my blog. All data has to be in JSON format. I've written article on JSON and WordPress, here is JSON formatted blog that has all recent posts http://alexbachuk.com/api/getrecentposts/
- First, let's add some simple html boilerplate
- Include 3 libraries: jQuery, Underscore, Backbone
- Create app.js script file and include it after 3 libraries (preferably before closing