Backbone.js is a lightweight JavaScript library that allows users to create and structure client side applications that run in a web browser. It offers a MV* (Model-View-*) framework which abstracts data into models, the DOM into views and ties these two together utilizing events.

Jeremy Ashkenas was the creator of Backbone.js and the first release was on the 13th of October 2010.

Backbone.js is mainstream, mature and has both a dynamic developer group as well as an abundance of plugins and extensions accessible that build upon it. It has been utilized to make significant applications by companies such as, Disqus, Walmart, SoundCloud and LinkedIn.

What is backbone.js good for?

Backbone.js is good for its organization of .js files. It provides a good assortment of base classes that can be used to write clean JavaScript code that interfaces with RESTful endpoints on your server. Furthermore, Backbone.js is very helpful for a developer because you are given the opportunity to do anything you wish for rather than attempting to fork through the programming api and modify. Backbone.js is also good for its straightforwardness and simplicity of implementation.

The following are the advantages of using backbone.js :

js make the creation of applications and front-end much less demanding by better utilising JavaScript functions.

js gives different building blocks for example, models, views, events, routers and collections for client side web applications.

At the point when the model changes, it consequently updates the HTML of your application.

js is a straightforward library for isolating business and client interface logic.

It is free and open source library and contains more than 100 accessible extensions.

It acts like a backbone for your tasks and helps to organize your code

It deals with the data model which incorporates the client data and showcases that data at the server side with the same format used for client side.

It has soft dependency with jQuery and hard dependency with Underscore.js.

It permits the creation of front-end web applications or mobile applications in a very organized and structured format.



Example and code snippets

Let's create a simple example using Backbone.js.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Hello World using Backbone.js</title> </head> <body> <!-- ========= --> <!-- Your HTML --> <!-- ========= --> <div id="container">Loading...</div> <!-- ========= --> <!-- Libraries --> <!-- ========= --> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script> <!-- =============== --> <!-- Javascript code --> <!-- =============== --> <script type="text/javascript"> var AppView = Backbone.View.extend({ // el - stands for element. Every view has an element associated with HTML content, will be rendered. el: '#container', // It's the first function called when this view is instantiated. initialize: function(){ this.render(); }, // $el - it's a cached jQuery object (el), in which you can use jQuery functions to push content. Like the Hello backbone.js in this case. render: function(){ this.$el.html("Hello backbone.js!!!"); } }); var appView = new AppView(); </script> </body> </html>



The code comments are self explanatory. But let's add few more details as below:

There's html code at the start of body tag

<div id="container">Loading...</div>



This prints “Loading…”

Next, we have added the following CDNs

<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js" type="text/javascript"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js" type="text/javascript"></script>



Next we have the following script:

var AppView = Backbone.View.extend({ // el - stands for element. Every view has an element associated with HTML content, will be rendered. el: '#container', // It's the first function called when this view is instantiated. initialize: function(){ this.render(); }, // $el - it's a cached jQuery object (el), in which you can use jQuery functions to push content. Like the Hello World in this case. render: function(){ this.$el.html("Hello backbone.js!!!"); } });

var appView = new AppView();

The last line, we are initializing new AppView(). This will print the "Hello backbone.js!!!" in the div with id="container"

After executing, we should investigate each Backbone.js class object and figure out whether a “simple” application really needs the functionality given.

Here is an example Backbone View class:

var View = Backbone.View.extend({ // Represents the actual DOM element that corresponds to your View el: 'body', // Constructor initialize: function() { }, // Event Handlers events: { "click #example": "doSomething" }, render: function() { // Updates the text of the element with an ID attribute of example this.$el.find("#example").text("This is an example"); }, doSomething: function() { // Do something } });

Here is an example Backbone Model class:

var Model = Backbone.Model.extend({ // Default properties defaults: { example: "I love having my data separated from the DOM" } // Constructor initialize: function() { }, // Any time a Model attribute is set, this method is called validate: function(attrs) { } });

Here is an example Backbone Collection class:

var Collection = Backbone.Collection.extend({ //Allows the Collection to work with User models model: User });

Here is an example Backbone Router class:

var Router = Backbone.Router.extend({ // Constructor initialize: function(){ //Required for Backbone to start listening to hashchange events Backbone.history.start(); }, routes: { // Calls the home method when there is no hashtag on the url '': 'home' }, 'home': function(){ // Gets called when there is no hashtag on the url console.log("My very first Backbone route"); } });



Here is an example Event being triggered by a Backbone Model class:

var Model = Backbone.Model.extend({ // Default properties defaults: { example: "I love having my data separated from the DOM" } // Constructor initialize: function() { }, // Any time a Model attribute is set, this method is called validate: function(attrs) { }, triggerEvent: function() { // Triggers an test event and passes data that can be accessed in the event handler this.trigger("test", { someData: "data" }); } });

Here is an example Event being bound by a Backbone View class:

var view = Backbone.View.extend({ // Represents the actual DOM element that corresponds to your View (There is a one to one relationship between View Objects and DOM elements) el: 'body', // Constructor initialize: function() { //Setting the view's model property. This assumes you have created a model class and stored it in the Model variable this.model = new Model(); //Event handler that calls the initHandler method when the init Model Event is triggered this.model.on("test", this.test); }, // Event Handlers events: { "click #example": "testModelEvent" }, render: function() { // Updates the text of the element with an ID attribute of example this.$el.find("#example").text("This is an example"); }, promptUser: function() { prompt("Isn't this great?", "Yes, yes it is"); }, testModelEvent: function() { this.model.triggerEvent(); }, test: function(obj) { console.log("Just got " + obj.someData + " from my model!"); } });

Conclusion

Hopefully this article has helped you see the simplicity and ease in which Backbone.js can be used. The magnificence thing about Backbone.js is its effortlessness and straightforwardness. Backbone.js is an extraordinarily small library for the amount of functionality and structure it gives you. It is basically MVC for the front-end allowing you to make your code modular. In this article we’ve just touched upon the basic concepts of Backbone.js but if you intend to learn more about it, there are a wealth of references available on the web.