Introduction

Let's dive into the world of Backbone.js.

Before moving into the basics of Backbone.js just have a look at the official definition of Backbone.js:

“Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling and connects it all to your existing API over a RESTful JSON interface.”

Backbone.js is basically a light-weight JavaScript library that provides flexibility in web development. It adds an amount of functionality and structure to client-side code. It enforces the communication with the server using the RESTful API. Backbone.js is not a framework.

These libraries are used to create Single-Page Applications (SPAs).

In Backbone data is represented as Models that can be manipulated in various ways (including created, deleted, validated and saved to the server). It keeps front-end code modular and organized.

The attribute of a Model is changed after UI action, the Model triggers a changed event. Accordingly all the views will also be notified of the change. Simply put, when the model changes the views simply update themselves.

All the prototypes of Backbone.js are instantiated with the "new" keyword. There is an initialize() function that is called at the time of the instantiating of the prototypes of Backbone (Views, Models, Collections and Routers).

Backbone Structure: Backbone provides the various tools to introduce structure into client-side applications.


Modules of Backbone.JS

These are the following modules:

Let us taste the basics of these modules.

Views

If you have a basic knowledge of MVC, Views are just like "Controllers" in MVC. If you are unfamiliar with MVC frameworks then no worries. Here we will try to explain in a simple way.

A view's render() method can be bound to a model's change() event, enabling the view to instantly reflect model changes without requiring a full page refresh.

Backbone's Views

Takes user events (clicks, pressed keys, and so on) and perform accordingly.

Render HTML views and templates.

Interact with models that contain the data of the application.

Events

Events are a module that can be mixed in to any object. Events provide the object the ability to bind and trigger custom named events. Events are not declared before they are bound. They may take arguments. For example:

  1. var object = {};
  2. _.extend(object, Backbone.Events);
  3. object.on("alert", function (msg) {
  4. alert("Triggered " + msg); });
  5. object.trigger("alert", "an event");
Output



Model

Models are the heart of every application.

They contain the interactive data and the logic surrounding it, such as data validation, default values, data initialization, conversions and so on.

Collections

Backbone collections are simply an ordered set of models such that it can be used in situations such as:

Model: Student, Collection: School
Model: Animal, Collection: Zoo

Router

Backbone routers are used for routing application URLs when using hash tags(#). It also enables us to use browser navigation with Single-Page Applications.

Actually routes facilitate the possibility of having deep copied URLs and history provides the possibility of using the browser navigation. A Router interprets anything after "#" tag in the URL.

Creating a backbone Router

Similar to various modules of backbone are JavaScript modules created by extending the Router class of backbone.

  1. var routers = Backbone.Router.extend({
  2. routes: {
  3. },help: function() {
  4. ... },
  5. search: function(query, page)
  6. { ... } });

Backbone.History: It handles hashchange events in our application. This will automatically handle routes that have been defined and trigger callbacks when they've been accessed.

The Backbone.history.start() method will simply tell Backbone that it's okay to begin monitoring all hashchange events.

Note

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.


Backbone.js code sample

Here I am trying to present a simple code sample in which I will be using nearly all the modules of Backbone.js like View, Collection, Model and Events.

In this example I am using the 3 JavaScript Libraries Backbone.js, jQuery, Underscore.js.

We need to create a HTML file for front view and add JavaScript code to it.

  1. <!DOCTYPE html >
  2. <html>
  3. <head>
  4. <title>Backbone.js By Shridhar</title>
  5. <script type="text/javascript"
  6. src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  7. <script type="text/javascript"
  8. src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
  9. <script type="text/javascript"
  10. src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
  11. <script type="text/javascript"
  12. src="sampleTask.js"></script>
  13. </head>
  14. <body>
  15. <input type="text" id="txtinput" placeholder="Add items" />
  16. <button id="input">Click to Add</button>
  17. <ul id="itemslist"></ul>
  18. <script type="text/javascript">
  19. $(function() {
  20. ItemList = Backbone.Collection.extend({ // creating collection
  21. initialize: function() {
  22. }
  23. });
  24. ItemView = Backbone.View.extend({ // creating view
  25. tagname: 'li',
  26. events: {
  27. 'click #input': 'getitems'
  28. },
  29. initialize: function() {
  30. var thisView = this;
  31. this.itemlist = new ItemList;
  32. _.bindAll(this, 'render');
  33. this.itemlist.bind("add", function(model) {
  34. thisView.render(model);
  35. })
  36. },
  37. getTask: function() {
  38. var task_name = $('#txtinput').val();
  39. this.itemlist.add({ name: task_name });
  40. },
  41. render: function(model) {
  42. $("#itemslist").append("<li>" +
  43. model.get("name") + "</li>");
  44. console.log('rendered')
  45. }
  46. });
  47. var view = new ItemView({ el: 'body' });
  48. });
  49. </script>
  50. </body>
  51. </html>
Output



Add some items:



Items will appear in the list after the Click event, in other words after clicking “Click to Add”.



How the preceding code works

In the preceding code, we are trying to add the value in the collection in the HTML list element. Initially we created a collection by extending Backbone. For the collection, similarly we create a view that takes user events (clicks, pressed keys and so on) and performs accordingly. After a "click" event occurs, the getitems method will be called that will get the values from the input type we use. After getting the items from the input types, items will be added to the Itemlist. The collection.render() method is responsible for displaying that collection in the HTML element, for that purpose we had to use a list element.

Model in Backbone.JS : Part 2 >>