Top 20 Backbone.js Interview Questions

By | January 29, 2017
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

Today, we are going to cover another topic in Technical Interview Questions and Answers Series i.e. Backbone.js. Previously, we explored various JavaScript Libraries and Frameworks including jQuery, AnguarJS 1.x & AngularJS 2.0, ReactJS, NodeJS etc and you can follow to read more related here. We tried to cover the maximum areas in each Technology so that reader at each level (Beginner or Intermediate or Advanced one) can take advantage from it.Backbone JS Interview Questions

BackboneJS is another famous JavaScript Library, we will explore all various features by following Interview Question and Answer pattern as we did earlier.

Backbone.js Interview Questions PDF version will be available later for download.

Backbone.js Interview Questions List

What is Backbonejs? What are the key advantages of using Backbone.js? Is there any downside using BackboneJS?

What is Backbone.js?

Backbone.js is mainly a light weight JavaScript library rather than a framework which is used to structure code in a large scale application or a single page web application. The other features of backboneJS are as follows:

  • It follows Model-View- Controller (MVC) architecture.
  • It provides functionality to access database and manipulate data.

What are the key advantages of using BackboneJS?

  • It provides minimal set of data structure only Model and Collection to develop applications ranges from embedded widget to large scale.
  • Views and URL are user interface which are capable of binding to model and event.
  • There is no performance drawback of using backboneJS in large scale application.
  • It provides dynamic Model – View and Model – Event binding.
  • The main feature of backbone.js is that it provides a way to manage and organize code.

Downside using Backbone.js?

It is not a complete framework, therefore in the era of ReactJS and AngularJS the usages of BackboneJS is very few and its getting to be obsolete day by day.
Back to top

How Backbone different from other JavaScript Frameworks like AngularJS, ReactJs etc.

Framework Engine:

Backbone.js does not provide framework engine, on the other hand, emberjs, angularjs and reactjs provide their own framework engine.

Template Engine:

Angular, Ember and React provides their template engine for development, however backbone allow user to choose independently.

However, backbone.js is light, easy to learn and easily adoptable.

BackboneJS Vs AngularJS Vs ReactJS Vs Ember?

According to the google trend, backbonejs gained some popularity around 2012. However, after 2014, backbone.js has lost its popularity to reactjs and angularjs.Backbone Vs Angular Vs React

Back to top

How to set up environment for BackboneJS? Explain by following a step by step approach.

  • Create a new folder with the name same as project name.Backbonejs Project
  • Create a file called index.html. This is the main html  file for the app.Backbonejs Libraries
  • Now organize folders for different components inside the folder called ‘components’. For each components there will be a folder for models, a folder for collections and a folder for views and html templates. For example, here is the folders and files for ‘book’ component.Components in Backbonejs
  • Create a folder for routers called ‘routers’.
  • Create folder for assets.
  • Finally, the folder structure for the project will look as following:Backbonejs Example App
  • On index.html.
     

Back to top

What are the main components of Backbone.js? Discuss in detail the architectural style of BackboneJS Application with the help of a diagram.

What are the main components of Backbone.js?

The main components of backbone.js are as following:

  • Events
  • Backbone.Model
  • Backbone.Collection
  • Backbone.Router
  • Backbone.Sync
  • Backbone.View

Backbone.js Application Architecture

Events:

Events are the core component of backbonejs. This is the basic way of controller. Events is accessible by an instance of Model, Collection, View, Router and History. Therefore, any instance of Model, Collection, View, Router and History can dispatch and listen to event to which they are bind to.  The global ‘Backbone’ can also access events as following:

The second parameter which is a function is registered as a handler to be called when a specific event by the name passed as the first parameter occurs. Similarly, for any instance of any model can access Event.

For example, if an object called Obj1 wants to notify another object whenever it gets changed, it can dispatch the notify event. Any object interest to listen to the change of Obj1 can bind to the ‘notify’ event and can listen to when Obj1 gets changed and can perform necessary action they require. Obj1 does not need to know who is listening to it’s notify event and what they are performing on it’s change.

There are some core events such on, off, listento and trigger.

Backbone.Model:

In a MVC framework like backbone.js, Model is the main fundamental concept. A model is a representation of any component use in application. Therefore, a model can be represented as following:BackboneJS Model

Each Model in Backbone js are created by extending Backbone.Model.

Here default is used if we want to set any default attribute to every instance of the Model.

Now if we create an instance of Book Model as following:

Every time a new instance of a Model will be created, the initialized will be called. On the console, the output would be:Backbone Model Output

Backbone.Model provides getter and setter in order to access the Object directly. If we want to access the title attribute of Book Model for any of its instance we just need to access as book1.get(…). Similarly,  Backbone.Model provides setter to change any of it’s attribute.

The output of getter and setter would be as following:Model getter and setter

It is possible to use  on event to detect change in any of the instance for example,

The output would be:Backbone Model Getter Output

Backbone also supports model validation through model.validate() . For example:

Here , the validate method of the Book model defines the required attribute of Book object and define the corresponding error message. Now by using {validate: true} while creating an instance of the Model. For example:

Here is the output, as description attribute for the instance book1 has not been given.Backbone Description Attribute

Backbone.Collection:

The next component for backbone.js is collection. Collection is usually a list of instance of a particular Model which is created by extending Backbone.Collection. Every collection is bind to a Model. Here is an example of a collection of Objects of type Book Model.

Now if we create an instance of the collection as following:

The output would be as following:Backbone Collections

Backbone.Router:

Routers are created by extending Backbone.Router which gives the way to communicate between different action, events and view. This is just like a default navigation for Backbone.js application. Router are triggered or started by Backbone.History. Usually it is recommended to have a single router parent for an application.  Router.navigate() is another function of Router class which is triggered in order to change the the route along with updating the URL by passing the trigger:true option.

Backbone.Router can also be bound to event as like Model, Collection and View. On triggering “route” event on the router, it is possible to control the navigation as following:

Backbone.Sync:

Every time there is a read, save, or delete models operation, Backbone.sync is called. It makes RESTful requests using jQuery. This can be overridden.

Backbone.View?

Backbone View is used to represent any Model or collection on the DOM of HTML. Therefore, View is usually a HTML element which is added to the DOM of the Html Page. If there is any user action such as keyup, keydown, corresponding view of the element get notified. If there is any change in the model that is being represented by the View, the view get notified and can take necessary action defined.  Backbone.View class is also kind of a controller, dispatch events and change the DOM element accordingly.

Back to top

 What is Backbone JS Event? Explain event handling in backbone.js with an example.

BackboneJS Events can be bound to view, model and collection. Therefore, it is possible every time there is a change in any of these three main components of BackboneJs, corresponding event triggered.

Therefore, every view can be connected to particular event.  According to the above example, every time there is a key up event occur on the input html element with id ‘input-text’, the corresponding method ‘change’ will be triggered.

Similarly, event can be bounded to Collection, Model and View element as well.

Back to top

How to Read files (JSON) in BackboneJS.

Backbone.Collection can be defined using JSON File. For example, if we have a JSON file called books.json with a number of instance of Model Book.

And Now if we want to create Collection instance using the JSON file. We can use fetch method of Backbone.Collection.

The output would be as following:JSON in Backbone

Back to top

How to implement HTTP Requests, for example GET, POST, PUT and DELETE using Backbonejs? Explain With example?

BackboneJS does not provide own framework, therefore, it requires separate framework for making HTTP request.  Therefore, it requires third party library for example Express.js and Node.js.

  • Install NodeJS.
  • Inside the project folder, create a package.json file.
  • Install libraries using ‘npm install command’.
  • Create a server.js file.
  • Run the script ‘node server’.

Back to top

Explain History and its usage with example?

Backbone.History is used to keep track of the navigation history of different routes, it is also used to match the appropriate route, fires callbacks to handle events. Therefore, Backbone.History enables routing in application.

The first requirement of enabling routing in the application is to create a router extending Backbone.Router. The next step is to create an instance of the router, for example:

  • This start method of Backbone.History starts listening to routes and manages the history.
  • It monitors the trigger of ‘hashchanged’ which is trigger every time the route is changed. This method can be called once.
  • Any subsequent calls to Backbone.history.start() will throw an error, and it will return the Backbone.History.started variable which is a boolean value indicating the status of History monitoring either started or not.
  • Backbone.history.start([options]), this can receive a parameter options. For modern browser, this options can be  {pushState: true} and for old browser, that does not support pushState, this can be ‘{hashChange: false}’.
  • Backbone.history.start() returns true. If no defined route matches the current URL, it returns false.
  • It is recommended to call start() only after the DOM is ready.

Another method of Backbone.History is navigate. For example, once a model has been saved if we want to redirect the navigation to the index page, it could be done as following:

Back to top

How to use child views? Explain with example.

  • In index.html page create a container for the IndexView.
  • Create a new view called BookIndexView.
    This View has a method called ‘addChildView’ which will be used to add child View in the parent View.
  • The html template for BookIndex view is as following:
  • Now Lets create the child View for each Book. Where each book View would look like:ChildView in BackboneJS
  • The Html template for BookView book.html.
  • The Javascript for BookView.
  • In index.html include book.js book_index.js.
  • Now if we render BookIndexView as following:
    The output Would be:BackboneJS List Child View
  • Now if we add a child View as following:
    Output would be:List ChildView Backbone Tutorial
    If we add one more it would look like:
    Output would be as following:BackboneJS ChildView Tutorial

Back to top

What is Collection in Backbone.js? Explain with example.

Collections are set of Model created by extending Backbone.Collection. Collections are used to represent an array of object.

To create a collections in Backbone.js application, it is required to create an object of type model. This object need at least one property which is required. The new collections would be a set of this created model.

For example:

Output:Backbone Collection Tutorial

Event Handling in Collections:

It is possible to declare event in order to change the collections.

Back to top

More Practical Interview Questions with Answers below:

How to bind model to view?

Inside the initialize function, we can use listenTo method of View. Another way is to use the binding method on of any model.

Back to top

How to bind Model to event?

  • Define the default field of of any Model, here title, description, author, yearPublished and rating are the default fields of Book Model.
  • Inside the initialize method of the Model, it is possible to map different event for different field of the Model object.
  • For example, here if the author field of the model is changed it would trigger ‘change:author’ event that will call notifyAuthor fucntion. Similarly if only ‘change’ event is triggered , corresponding function notifyGeneral will be invoked. For ‘change:title’ event, ‘notifyTitle’ method will be invoked.
    On the first line in above example, the title of book object of Model type Book has been updated , therefore a ‘change:title’ event has been triggered. Therefore, corresponding method notifyTitle would be invoked and the console output would be:

    title change

    On the second line for the object book2, author has been changed, therefore, a ‘change:author’ event has been triggered and notifyAuthor method would be invoked so the output would be:

     author changed

  • We can directly invoke method to change any field of the model. In this example, increamentRating function increases the rating field of Book Model by one, where decreamentRating function decrease the rating field of Book Model by one.
    increamentRating on book object can be triggered as following:

    The corresponding output would be:

    ratting ++

Back to top

How to Render View? Explain with Example.

  • In the index.html add a placeholder <div> with Id=container-book. This div will be the DOM element for the new view.
  • Create a book View Model in book_view.js file. This view has several options such as className, template, render and initialize. Template is used to define the html template for the new view. Backbone.View has its own render function however that does not do anything. This existing render function is just an abstraction given by backbone.js. Therefore, we have to override ‘render’ function in the new ‘BookView’.
    In our render function, we have append the JSON form of the passed model to the view and append the JSON format of the model to  the “el” property of the view. In addition, jQuery find the element in the DOM with the id of “container-book” as mentioned earlier and assign the html of “el” to the element. In the render function, a model is passed and the model data is appended to the template function and finally, render function return the html result.
  • The next step is to create a variable of type Book Model. And create a variable bookView of type View called ‘BookView’.
  • In the index.html create a method which will be called once jQuery finished the document to be ready.

Back to top

What is Template? How to use Template in Backbone.js?

Template is one of the core component that I used for the View. Basically, this is the html DOM elements for any View. Backbonejs has dependency on Underscore Js in order to compile template. _template function from underscore is used for compiling template.

Template can be used directly without using any view.

  • A div need as a placeholder for the template to be viewed in DOM. Lets put an id ‘book1-container’.
  • Create the Model book1 which will be passed to the template as data.
  • Create a string called template just representing the title from Book Model.
  • _template function will take the string template and compile it to make it ready to be rendered.
  • Then the placeholder will append the compiled template with the data from passed object (book1).

It is also possible to define the template using text/template script as following:

Now the id =’template-book1’ will be will be used to obtain Html template using jQuery as following.

It is also possible to user template from another file such as following:

Back to top

What is Router? Explain with Example.

In order to navigate between pages and different request, Backbone.js supports Router. Therefore, it is easily navigable.

Andrew de Andrade, the creator of backboneJS has mentioned that in a application, there will be only one route. It is conventional to have a single route for the entire application.

This has all the different route in it. On initialization of the router, the index method is called, therefore,  BookIndexView is Initialized and has been rendered. The history is also started monitoring the hashchanged events.

Now if we click the Delete Button on the Index View:Backbone Routes Tutorial

The corresponding Book will be deleted and it will again navigated to the /index URL and BookIndexView will be initialized again,BackboneJS Routes

And the three book can be viewed:Backbone Routes Tutorial Output

Back to top

What is Utility? Explain with Example.

Backbone.js Utility class define the following two methods:

Backbone.noConflict

var backbone = Backbone.noConflict();

This method returns the Backbone object back to its original value. Instead of using the global Backbone Object it is possible to use a local instance of Backbone by using this method Backbone.noConflict(). Usually in order to embed Backbone on third-party websites, where we don’t want to mix the Backbone instance with other backbone module it is very useful to use a local reference without messing with existing Backbone.

Backbone.$

Most of the time in a website where there can be number of other third party jquery based module are running, different version of jquery can conflict with each other. At that moment among all the multiple copies of Jquery , this method helps to use a perticualr one

Or can use requires to point to a particular version of the Jquery

Back to top

What is Converter? Explain with Example.

Backbonejs support a functionality that called converter. This function helps to copy models attribute to a html attribute and vise versa.

Basically this is used for two way data binding.

There are different way two way binding is possible. For example using Epoxy.js from https://github.com/gmac/backbone.epoxy/blob/master/backbone.epoxy.min.js

  • Download and add it to the index.html as following:
  • Create a Model.
  • Create an Proxy View.
  • Load the View.
  • The Html Template.
  • Output would be:Backbone Converter Example Tutorial
  • As the Input text change the span first-name and last-name will be changed as we type in the input box

Back to top

How to Configure Jasmine to execute Unit Testing? Explain with Example.

  • Download jasmine from ‘https://github.com/jasmine/jasmine/releases’ and extract inside libs folder.
  • Create a spec page to write the unit testing those will be performed on Book Model.
  • Inside the function all the necessary unit testing need to be defined as following:
  • Create a specrunner html page.
    Now running the specrunner , it will run each of the unit test described in the spec.

Back to top

How to Config MongoDB and Setup Connection in Backbone.js Application?

Mongodb can be used with Backbonejs directly by using the third party library backbone-mongodb. Following are the steps:

  • Add ‘backbone-mongodb.js’  file on the header of index.html
  • Enable  the app config.
  • Create Model Extending Backbone.MongoModel instead of Backbone.Model. For example,
    Backbone-mongodb overrides Backbone.parse() and Backbone.sync() methods to convert MongoDB Extended JSON to normal JSON.
  • Create a collection.
    Now use the Backbone Router to access different CRUD operation.

Back to top

How to prevent Memory Leaks in Backbone.js Application?

Backbone.js is not a complete framework, it needs other framework to reply on. Therefore, most often developers use Marionette in order to perform memory management. As stated on the Chrome Developer Tools – JavaScript Profiling site,

“A memory leak is a gradual loss of available computer memory. It occurs when a program repeatedly fails to return memory it has obtained for temporary use. JavaScript web apps can often suffer from similar memory related issues that native applications do, such as leaks and bloat but they also have to deal with garbage collection pauses.”

In backbone.js application , memory leak is often occurred durig pushing nested view to a parent view. Therefore it is necessary to keep track all the nested view and add them or remove them correctly.

Back to top
That is all we have about Backbone.js Interview Questions and Answers. Next we will come up with more related Interview Questions and Answers. You can follow the below given other web development interview questions and answers to improve your technical skills.

More Related and MEAN Stack Tutorial

Following MEAN Stack & Related Tutorials will be helpful to practically grasp the technology.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest