Google News
logo
Backbone Interview Questions
Backbone.js is a light weighted client-side (front-end) web framework based on JavaScript. It is used to develop client-side applications which run on a web browser. Developing client-side applications in Backbone.js is pretty easy and consumes a lesser amount of time. It makes developing single-page applications also easier. It supports MVC (Model, View, and Controller) architecture.
 
Model : Model is a part of the code that populates and retrieves the data

View : View is nothing but the HTML representation of this model. If you make any model changes, this will instantly reflect in the View.

Controller : The controller makes you able to save your JavaScript application via an URL.
Backbone.js is mostly used in building single-page web apps or complicated user interfaces will get extremely difficult by simply using jQuery or MooTools. The problem is standard JavaScript libraries are great at what they do – and without realizing it you can build an entire application without any formal structure. You will with ease turn your application into a nested pile of jQuery callbacks, all tied to concrete DOM elements.
Main components of Backbone.js :
 
Model : It performs various types of action on the data like validation, conversion, computed properties, access control.

View : It specifies how your data looks like.

Collection : It handles the loading and saving of new models to the server.

Router : It is used for routing client-side applications and connecting them to actions and events.

Event class object : It facilitates the objects to bind and trigger the custom events by using the desired name of our choice.
Backbone.js is required in following conditions :
 
* When you are developing a web application that requires a lot of JavaScript.
* It is required when you want to give structure to your code if your application needs to be scalable.
* Backbone is useful when a web application has to work with jQuery to traverse the DOM or give animations.
* When model changes and you want to update the HTML application automatically.
Some feature of Backbone.js are:
 
* It makes your code simple, systematic and organized. It acts like a backbone for your project.
* Backbone also works to taunt DOM manipulation libraries, templates and router together.
* It is used while building a web application with complex liftings for view rendering as well as database interaction.
* It allows developers to develop one-page applications and front-end much easier and better using JavaScript functions. 
* It creates client-side web applications or mobile applications in well-structured and organized format.
* It provides different types of building blocks like models, views, events, routers and collections for assembling client-side web applications.
* It is a simple library used to separate business and user interface logic.
* It is a free and open source library and contains over 100 available extensions.
* Backbone.js manages the data model which includes the user data and display that data at the server side with the same format written at client side.
A Collection can be defined as an ordered set of modules. In Backbone.js, there is a collection class which provides some useful methods to deal with the collections. We can extend the collection class to provide some additional functionalities. For example :
<script type="text/javascript">    
        //The model 'MyTeam' includes default values and  extended using the Backbone.Model class    
         var MyTeam = Backbone.Model.extend({    
            defaults: {    
               player: "Dhyanchand",    
               country: "India"    
            },    
         });    
    
         //'MyTeam1' is an instance of the collection    
         var MyTeam1 = Backbone.Collection.extend({    
            model: MyTeam  //model 'MyTeam' is specified for a collection by overriding the 'model' property    
         });    
    
         //The collection 'MyTeam1' is instantiated by using new keyword    
         var myval=new MyTeam1({});    
    
         //The JSON.stringify() method returns values of collection in the JSON format    
         document.write("The values in the collection are: ",JSON.stringify(myval));    
 </script>

 

Following are the three js files that we require to setup Backbone.js and make a working environment :
 
* jQuery
* Backbone
* Underscore

In our application, we have to put these files within the js folder and use it on our index.html page.

Backbone.js routers are used to route the application's URL to some particular actions and events. At least one route must be present for every defined router. It also defines the URL representation of the application's object when web applications provide linkable, bookmarkable, and sharable URL.
 
<script type="text/javascript">    
        var RouteMenu = Backbone.View.extend({    
           el: '#routemenu',  //'el' defines which element to be used as the view reference    
           events: {    
              'click a' : 'onClick'    
           },    
           onClick: function( e ) {    
              router.navigate('/');    
           }    
       });    
       var Router = Backbone.Router.extend({    
          routes: {    
             'route/:id' : 'defaultRoute'    
          },    
       });    
       var routemenu = new RouteMenu();    
       Backbone.history.start();    
</script>

 

Backbone.js event can be defined as the module which can be mixed with any object. There are following methods which are used to manipulate Backbone.js events,
 
on - It binds an event to an object and executes the callback whenever an event is fired.
off - It removes callback functions or all events from an object.
trigger - It invokes the callback functions for the given events.
once - It extends the backbone model class while creating your own backbone model.
listenTo - It informs one object to listen to an event on another object.
stopListening - It can be used to stop listening to events on the other objects.
listenToOnce - It causes the listener, to occur only once before the callback function is being removed.
Backbone.js is required in following condition
 
* When developing a web application that requires a lot of JavaScript
* It is required when you want to give structure to your code, if your application needs to be scalable
* Backbone is useful when a web application has to work with jQuery to traverse the DOM or give animations
Advantages of Backbone.js :
 
* You can develop a web application with Backbone.js by using JavaScript with the minimal set of data-structuring (models & collections) and user interface (views & URLs).

* It is best for developing MVC like web applications, single page web applications or complex JavaScript web applications in an organized and structured manner without JavaScript code mixing with HTML.

* It provides API with many functions.

* It provides a key-value binding and custom events.

* It facilitates you to abstract your data into models and your DOM application into views and binds the two together using events.
For multiple page web app in backbone.js there are lots of consideration but here are two which can be useful
 
Serving the page : In this, where you want to have your web server route everything to the server route everything to serve the same static page. That means that everything in https://freetimelearning.com/* will serve /var/www/freetimelearning.com/index.php. once the static page is loaded, the JS on that page will decide what to do given the url

Push State : You can still use backbone routing to do your routing, but don’t use hashbangs.  This will allow you to navigate to URLs without actually needing a page refresh.
* To make synchronization process of views and models together, ModelBinder class is used.
 
* The most powerful capabilities of ModelBinder class is that it enables you to define scope when you create your bindings using jQuery.
 
* If your views are simple, you can rely on default scoping rules that are based off of the html “name” attribute.

* You can define scoping with jQuery selectors if your views are complex.
The Converter is a function which is used to convert the JavaScript object to a model. It is invoked when the transition is made between an HTML element and the model's attribute.
Sync is a function that is called every time. It attempts to read or save a model to the server. It persists the state of the model to the server.
Two methods can be used to manipulate the Backbone.js utility :
 
Backbone.noConflict : It returns the Backbone objects to its original value and provides a facility to store the reference to a backbone. It can be used to embed the backbone on third-party websites, where you don't want to thrash the existing backbone.

Backbone.$ : This property is used when you have multiple copies of jQuery on the page or want to tell Backbone to use a particular object as its DOM / Ajax library.
When you want to remove the validation binding on the model or all models , removing all events hooked up on the collection, you can use Unbinding function.
 
For example : Backbone.Validation.Unbind(view)   [ This will remove the validation binding]
There are the following configuration options available in Backbone.js.
 
* modelSetOptions
* boundAttributes
* supressThrows
* converter
* change Triggers
* InitialCopyDirection
In Backbone.js, the "id" property on a model is automatically assigned based on the "id" set in the model's attributes hash. This is the ID that we receive from the rest of API for the resource that we are querying. On the other hand, the "cid" is a temporary ID assigned to each model and is useful until an actual ID is assigned for the object.

For example, a model pushed to a collection that has not yet been persisted can be called "cid", until it is saved in the database and an actual ID is generated for it. After that, it can be called "id".
There are mainly two advantages to using "listenTo()" instead of using "on()" to bind event handlers. See the syntax of using these both because they are used differently :
 
Syntax :
 
listener.listenTo(object, event, callback)  
object.on(event, callback)  
 
While using "listenTo()", the object whose events you want to listen to is passed as the first argument. On the other hand, in the case of "on()", it is a method on that object.
 
The key advantages of "listenTo()" over "on()" are :
 
* The listener keeps track of all the event handlers, making it easier to remove them all at once when required.
* The callback's context is always set to the listener itself.
In Backbone.js, by default, collections are not explicitly sorted. We can sort the collections by defining a comparator on the collection object. By defining a comparator, a collection is sorted whenever a model is added or the "sort()" method is invoked on a collection :
 
Example :
var Fruits = Backbone.Collection.extend({  
    comparator: function(a, b) { /* .. */ }  
})  
// Or  
var Fruits = Backbone.Collection.extend({})  
var fruits = new Fruits()  
fruits.comparator = function(a, b) { /* .. */ }  
 
The comparator property can be a function with one argument or two arguments (similarly used in "sort"), or a string identifying the attribute by name to sort on.
 
When an attribute of a model in a collection changes, the collection doesn't sort itself. In this case, the sort must be invoked explicitly to update the order of models in the collection.
Backbone.sync is a function that is Backbone js call every time it attempts to read or save a model to the server.By default, it uses jQuery.ajax to make a RESTful JSON request and returns a jqXHR
 
Example Code :
Backbone.sync = function(method, model) {
  alert(method + ": " + JSON.stringify(model));
  model.set('id', 1);
};

var author= new Backbone.Model({
  author: "Sharad",
  website: "https://www.freetimelearning.com"
});

author.save();

author.save({author: "FTL"});

 

If you are working with Backbone, Backbone models follow traditional REST. As mentioned in the docs for Backbone. Sync () :

* Create → POST /collection
* Read → GET /collection [/id]
* Update → PUT /collection/id
* Patch → PATCH /collection/id
* Delete → DELETE /collection/id

If you need to modify what verbs and endpoints are used for methods fetch (), save (), and destroy (), you can override Backbone.sync on a per model basis to accomodate custom endpoints and HTTP verbs.
A list of some prominent features or key points of Backbone.js:
 
Backbone.js has a hard dependency with underscore.js, making it more functional and providing support for a range of useful collection-based operations.

Backbone.js has a soft dependency on jQuery.

Backbone.js is based on MVC architecture. When the model changes, it can update the HTML of your application automatically.

Backbone.js uses a client-side rendering framework or Javascript templating to render HTML, enabling you not to embed HTML code inside JavaScript code.

Backbone.js offers a significantly clean and elegant way for UI updates and DOM manipulations.
Generally, Backbone.js is required in the following conditions :
 
* When we have to develop a web application that requires a lot of JavaScript codes.
* It is also required if your application needs to be scalable and give a structure to your code.
* Backbone is required when a web application works with jQuery to traverse the DOM or give animations.
It is not recommended to change the "el" property of a view directly because when you attempt to change the "el" property directly, it may lead to inconsistent behavior from the Backbone.js view. The reason behind this inconsistent behavior is that when you change the "el" property directly, it doesn't automatically update the cached jQuery object property corresponding to it, which is "$el".
 
The correct way to do this is to use "setElement()" on the view.
 
Syntax :
view.setElement(otherElement) 
 
Whenever you change some data within the model, the model objects fire the "change" event. However, the object fires another event with a name specific to the change attribute : "change:[attribute]".
 
For example :
 
var Fruit = Backbone.Model.extend({})  
var fruit = new Fruit({  
    weight: 3.25  
})  
fruit.on('change:weight, function() {  
    // Event "change:weight" will fire whenever the weight attribute of fruit changes.  
})​

 

 
In Backbone.js, the model.cid is a special property of models, the cid or client id, which is automatically assigned to all models when they are first created. The model.cid works as a unique identifier. This is very useful when the model is not saved to the server, but you want to show it on the UI.
The main function of to JSON in Backbone.js is to return a shallow copy of the model's attribute for JSON stringification. It does not return a JSON string and provides persistence, serialization, and augmentation before being sent to the server.
The Backbone.js attributes define a model's property and use the set() method to update the attributes. It is usually a form of the JSON object representing the model data on the server.
 
Syntax :
 
model.attributes    

Example :
<script type="text/javascript">    
  var  Person = Backbone.Model.extend();    
  var person = new Person();    
  person.set({ name: "Chanti"});    
  document.write(person.get('name'));   
</script>
Advertisement