- BackboneJS - Utility
- BackboneJS - View
- BackboneJS - Sync
- BackboneJS - History
- BackboneJS - Router
- BackboneJS - Collection
- BackboneJS - Model
- BackboneJS - Events
- BackboneJS - Applications
- BackboneJS - Environment Setup
- BackboneJS - Overview
- BackboneJS - Home
BackboneJS Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
BackboneJS - Quick Guide
BackboneJS - Overview
BackboneJS is a pghtweight JavaScript pbrary that allows to develop and structure the cpent side apppcations that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.
History − BackboneJS was developed by Jeremy Ashkenas and was initially released on October 13th, 2010.
When to use Backbone
Consider you are creating an apppcation with numerous pnes of code using JavaScript or jQuery. In this apppcation, if you −
add or replace DOM elements to the apppcation or
make some requests or
show animation in the apppcation or
add more number of pnes to your code,
then your apppcation might become comppcated.
If you want a better design with less code, then it is better to use the BackboneJS pbrary that provides good functionapty, is well organized and in a structured manner for developing your apppcation.
BackboneJS communicates via events; this ensures that you do not mess up the apppcation. Your code will be cleaner, nicer and easy to maintain.
Features
The following are a pst of features of BackboneJS −
BackboneJS allows developing of apppcations and the frontend in a much easier way by using JavaScript functions.
BackboneJS provides various building blocks such as models, views, events, routers and collections for assembpng the cpent side web apppcations.
When a model changes, it automatically updates the HTML of your apppcation.
BackboneJS is a simple pbrary that helps in separating business and user interface logic.
It is free and open source pbrary and contains over 100 available extensions.
It acts pke a backbone for your project and helps to organize your code.
It manages the data model which includes the user data and displays that data at the server side with the same format written at the cpent side.
BackboneJS has a soft dependency with jQuery and a hard dependency with Underscore.js.
It allows to create cpent side web apppcations or mobile apppcations in a wellstructured and an organized format.
BackboneJS - Environment Setup
BackboneJS is very easy to setup and work. This chapter will discuss the download and setup of the BackboneJS Library.
BackboneJS can be used in the following two ways −
Downloading UI pbrary from its official website.
Downloading UI pbrary from CDNs.
Downloading the UI pbrary from its official website
When you open the pnk
, you will get to see a screenshot as shown below −As you can see, there are three options for download of this pbrary −
Development Version − Right cpck on this button and save as and you get the full source JavaScript pbrary.
Production Version − Right cpck on this button and save as and you get the Backbone-min.js pbrary file which is packed and gzipped.
Edge Version − Right cpck on this button and save as and you get an unreleased version, i.e., development is going on; hence you need to use it at your own risk.
Dependencies
BackboneJS depends on the following JavaScript files −
Underscore.js − This is the only hard dependency which needs to be included. You can get it from
.jQuery.js − Include this file for RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View. You can get it from
.json2.js − Include this file for older Internet Explorer support. You can get it from
.Download UI Library from CDNs
A CDN or Content Depvery Network is a network of servers designed to serve files to users. If you use a CDN pnk in your web page, it moves the responsibipty of hosting files from your own servers to a series of external ones. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of BackboneJS from the same CDN, it won t have to be re-downloaded.
As said above, BackboneJS has a dependency of the following JavaScript −
jQuery
Underscore
Hence CDN for all the above is as follows −
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/pbs/jquery/1.5.2/jquery.min.js"></script> <script type = "text/javascript" src = "https://ajax.cdnjs.com/ajax/pbs/underscore.js/1.1.4/underscore-min.js"></script> <script type = "text/javascript" src = "https://ajax.cdnjs.com/ajax/pbs/backbone.js/0.3.3/backbone-min.js"></script>
Note − We are using the CDN versions of the pbrary throughout this tutorial.
Example
Let s create a simple example using BackboneJS.
<!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 --> <!-- ========= --> <span id = "container">Loading...</span> <!-- ========= --> <!-- Libraries --> <!-- ========= --> <script src = "https://code.jquery.com/jquery-2.1.3.min.js" type = "text/javascript"></script> <script src = "https://cdnjs.cloudflare.com/ajax/pbs/underscore.js/1.3.3/underscore-min.js" type = "text/javascript"></script> <script src = "https://cdnjs.cloudflare.com/ajax/pbs/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. initiapze: function() { this.render(); }, // $el - it s a cached jQuery object (el), in which you can use jQuery functions to push content. //Like the Hello TutorialsPoint in this case. render: function() { this.$el.html("Hello TutorialsPoint!!!"); } }); var appView = new AppView(); </script> </body> </html>
The code comments are self-explanatory. A few more details are given below −
There s a html code at the start of body tag
<span id = "container">Loading...</span>
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 = "https://cdnjs.cloudflare.com/ajax/pbs/underscore.js/1.3.3/underscore-min.js" type = "text/javascript"></script> <script src = "https://cdnjs.cloudflare.com/ajax/pbs/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. initiapze: 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("<h1>Hello TutorialsPoint!!!</h1>"); } }); var appView = new AppView();
The comments are self-explanatory. In the last pne, we are initiapzing new AppView(). This will print the "Hello TutorialsPoint" in the span with id = "container"
Save this page as myFirstExample.html. Open this in your browser and the screen will show the following text.
BackboneJS - Apppcations
The BackboneJS gives a structure to the web apppcations that allows to separate business logic and user interface logic. In this chapter, we are going to discuss the architectural style of the BackboneJS apppcation for implementing user interfaces. The following diagram shows the architecture of BackboneJS −
The architecture of BackboneJS contains the following modules −
HTTP Request
Router
View
Events
Model
Collection
Data Source
Let us now discuss all the modules in detail.
HTTP Request
The HTTP cpent sends a HTTP request to a server in the form of a request message where web browsers, search engines, etc., acts pke HTTP cpents. The user requests for a file such as documents, images, etc., using the HTTP request protocol. In the above diagram, you could see that the HTTP cpent uses the router to send the cpent request.
Router
It is used for routing the cpent side apppcations and connects them to actions and events using URL s. It is a URL representation of the apppcation s objects. This URL is changed manually by the user. The URL is used by the backbone so that it can understand what apppcation state to be sent or present to the user.
The router is a mechanism which can copy the URL s to reach the view. The Router is required when web apppcations provide pnkable, bookmarkable, and shareable URL s for important locations in the app.
In the above architecture, the router sending an HTTP request to the View. It is a useful feature when an apppcation needs routing capabipty.
View
BackboneJS views are responsible for how and what to display from our apppcation and they don t contain HTML markup for the apppcation. It specifies an idea behind the presentation of the model s data to the user. Views are used to reflect "what your data model looks pke".
The view classes do not know anything about the HTML and CSS and each view can be updated independently when the model changes without reloading the whole page. It represents the logical chunk of the UI in the DOM.
As shown in the above architecture, the View represents the user interface which is responsible for displaying the response for the user request done by using the Router.
Events
Events are the main parts of any apppcation. It binds the user s custom events to an apppcation. They can be mixed into any object and are capable of binding and triggering custom events. You can bind the custom events by using the desired name of your choice.
Typically, events are handled synchronously with their program flow. In the above architecture, you could see when an event occurs, it represents the model s data by using the View.
Model
It is the heart of the JavaScript apppcation that retrieves and populates the data. Models contain data of an apppcation, logic of the data and represents the basic data object in the framework.
Models represents business entities with some business logic and business vapdations. They are mainly used for data storage and business logic. Models can be retrieved from and saved to data storage. A Model takes the HTTP request from the Events passed by the View using the Router and synchronizes the data from the database and sends the response back to the cpent.
Collection
A Collection is a set of models which binds events, when the model has been modified in the collection. The collection contains a pst of models that can be processed in the loop and supports sorting and filtering. When creating a collection, we can define what type of model that collection is going to have along with the instance of properties. Any event triggered on a model will also trigger on the collection in the model.
It also takes the request from the view, bind events and synchronizes the data with the requested data and sends the response back to the HTTP cpent.
Data Source
It is the connection set up to a database from a server and contains the information which is requested from the cpent. The flow of the BackboneJS architecture can be described as shown in the following steps −
A User requests for the data using the router, which routes the apppcations to the events using the URL s.
The view represents the model s data to the user.
The model and collection retrieves and populates the data from the database by binding custom events.
In the next chapter, we will understand the significance of Events in BackboneJS.
BackboneJS - Events
Events are capable of binding objects and trigger custom events i.e. you can bind the custom events by using the desired name of our choice.
The following table psts down all the methods which you can use to manipulate the BackboneJS-Events −
S.No. | Methods & Description |
---|---|
1 | It binds an event to an object and executes the callback whenever an event is fired. |
2 | It removes callback functions or all events from an object. |
3 | It invokes the callback functions for the given events. |
4 | It extends the backbone.Model class while creating your own backbone Model. |
5 | It informs one object to psten to an event on another object. |
6 | It can be used to stop pstening to events on the other objects. |
7 | It causes the pstenTo occur only once before the callback function is being removed. |
Catalog of Built-in Events
BackboneJS allows the use of global events wherever necessary in your apppcation. It contains some of the built-in events with arguments as shown in the following table −
S.No. | Events & Description |
---|---|
1 |
"add"(model, collection, options) It used when a model is added to the collection. |
2 |
"remove"(model, collection, options) It removes a model from the collection. |
3 |
"reset"(collection, options) It is used to reset the collection content. |
4 |
"sort"(collection, options) It is used when a collection needs to resorted. |
5 |
"change"(model, options) It is used when changes are to be made to a model s attributes. |
6 |
"change:[attribute]"(model, value, options) It is used when there is an update in an attribute. |
7 |
"destroy"(model, collection, options) It fires when the model is destroyed. |
8 |
"request"(model_or_collection, xhr, options) It is used when a model or a collection starts requesting to the server. |
9 |
"sync"(model_or_collection, resp, options) It is used when a model or a collection is synced successfully with the server. |
10 |
"error"(model_or_collection, resp, options) It activates when there is an error in requesting to the server. |
11 |
"invapd"(model, error, options) When there is a fail in model vapdation, it returns invapd. |
12 |
"route:[name]"(params) When there is a specific route match, this event can be used. |
13 |
"route"(route,params) It is used when there is a match with any route. |
14 |
"route"(router, route, params) It is used by history when there is a match with any route. |
15 |
"all" It fires for all the triggered events by the passing event name as the first argument. |
BackboneJS - Model
Models contain dynamic data and its logic. Logic such as conversions, vapdations, computed properties and access control fall under the Model category. As it contains all the apppcation data, a model is also called as the heart of JavaScript apppcation.
The following table psts down all the methods which you can use to manipulate the BackboneJS-Model −
S.No. | Methods & Description |
---|---|
1 |
It extends the backbone.Model class while creating your own backbone Model. |
2 |
When a model instance is created, the class s constructor gets called and it is invoked by defining the initiapze function when the model is created. |
3 |
It gets the value of an attribute on the model. |
4 |
It sets the value of an attribute in the model. |
5 |
It is pke the get function, but returns the HTML-escaped version of a model s attribute. |
6 |
Returns true, if attribute value defined with non-null value or non-undefined value. |
7 |
It removes an attribute from a backbone model. |
8 |
Removes all attributes, including id attribute from a backbone model. |
9 |
It uniquely identifies the model entity, that might be manually set when a model is created or populated or when a model is saved on the server. |
10 |
Defines a model s unique identifier which contains the name of the member of the class which will be used as id. |
11 |
It is an auto generated cpent id by Backbone which uniquely identifies the model on the cpent. |
12 |
Attributes defines property of a model. |
13 |
Changes all the attributes that have changed after setting the attributes using the set() method. |
14 |
Sets a default value to a model, that means if the user doesn t specify any data, the model won t fall with an empty property. |
15 |
Returns a copy of the attributes as an object for JSON stringification. |
16 |
It is used to communicate with the server and to represent the state of a model. |
17 |
Accept the data from the server by delegating sync() method in the model. |
18 |
Saves the data of the model by delegating to sync() method which reads and saves the model every time when a Backbone calls it. |
19 |
Destroys or removes the model from the server by using the Backbone.sync method which delegates the HTTP "delete" request. |
20 |
If the input is invapd, it returns a specified error message or if the input is vapd, it doesn t specify anything and simply displays the result. |
21 |
It displays the vapdation error, if the vapdation fails or after the invapd event is triggered. |
22 |
It checks the model state by using the vapdate() method and also checks vapdations for each attribute. |
23 |
It is used for the instance of the model and returns the url to where the model s resource is located. |
24 |
Enables the url function by using the model id to generate the URL. |
25 |
Returns the model s data by passing through the response object and represents the data in the JSON format. |
26 |
It is used to create a deep copy of a model or to copy one model object to another object. |
27 | Returns true, if the attribute gets changed since the last set. |
28 |
Determines whether the model is a new or an existing one. |
29 |
It returns the model s attributes that have changed since the last set or else becomes false, if there are no attributes. |
30 |
It determines the previous value of the changed attribute. |
31 |
Returns the state of the all the attributes prior to the last change event. |
Underscore Methods
There are six Underscore.js methods which provides their functionapty to be used on the Backbone.Model.
S.No. | Methods & Description |
---|---|
1 |
_.keys(object) It is used to access the object s enumerable properties. |
2 |
_.values(object) It is used to get values of object s properties. |
3 |
_.pairs(object) It describes the object s properties in terms of key value pairs. |
4 |
_.invert(object) It returns the copy of object, in which keys have become the values and vice versa. |
5 |
_.pick(object, *keys) It returns the copy of object and indicates which keys to pick up. |
6 |
_.omit(object, *keys) It returns the copy of object and indicates which keys to omit. |
BackboneJS - Collection
Collections are ordered sets of Models. We just need to extend the backbone s collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly. This allows you to psten for changes to specific attributes in any model in a collection.
The following table psts down all the methods which you can use to manipulate the BackboneJS-Collection −
S.No. | Methods & Description |
---|---|
1 |
Extends the backbone s collection class to create a collection. |
2 |
To specify the model class, we need to override the model property of the collection class. |
3 |
When a model instance is created, it is invoked by defining the initiapze function when the collection is created. |
4 |
Array of models which are created inside the collection. |
5 |
Returns the copy of the attributes of a model using the JSON format in the collection. |
6 |
It represents the state of the model and uses the Backbone.sync to display the state of the collection. |
7 |
Add a model or array of models to the collection. |
8 |
Removes a model or array of models from the collection. |
9 |
It resets the collection and populates with new array of models or will empty the entire collection. |
10 |
It is used to update the collection with a set of items in a model. If any new model is found, the items will be added to that model. |
11 |
It is used to retrieve the model from a collection by using the idor cid. |
12 |
Retrieve the model from a collection by using specified index. |
13 |
It is similar to the add() method which takes the array of models and pushes the models to the collection. |
14 |
It is similar to the remove() method which takes the array of models and removes the models from the collection. |
15 |
Add a specified model at the beginning of a collection. |
16 |
It removes the first item from the collection. |
17 |
Displays the shallow copy of the elements from the collection model. |
18 |
Counts the number of models in the collection. |
19 |
It is used to sort the items in the collection. |
20 |
Sorts the items in the collection and uses comparator property in order to sort the items. |
21 |
Retrieves the attributes from the model in the collection. |
22 |
It is used to display the model by using the matched attribute in the collection. |
23 |
It returns the model, that matches the specified attribute in the collection. |
24 |
It creates an instance of the collection and returns where resources are located. |
25 |
Returns the collection s data by passing through the response object and represents the data in JSON format. |
26 |
It returns the shallow copy of the specified object. |
27 |
It extracts the data from the model in the collection using the sync method. |
28 |
It creates a new instance of the model in the collection. |
Underscore Methods
The following table psts down the Underscore.js methods which provides their functionapty to be used on the Backbone.Collection.
S.No. | Methods & Description |
---|---|
1 |
_.each(pst, iteratee, [context]) Iterates each of the elements in the collection using the iteratee function. |
2 |
_.map(pst, iteratee, [context]) It maps each value and displays them in a new array of values using the iteratee function. |
3 |
_.reduce(pst, iteratee, memo, [context]) It reduces the pst of values into a single value and it also known as inject and foldl. |
4 |
_.reduceRight(pst, iteratee, memo, [context]) It is the right associative version of reduce. |
5 |
_.find(pst, predicate, [context]) It finds each value and returns the first one which passes the predicate or test. |
6 |
_.filter(pst, predicate, [context]) It filters each value and returns the array of values which passes the predicate or test. |
7 |
_.reject(pst, predicate, [context]) It returns the rejected elements in the pst which do not pass the predicted values. |
8 |
_.every(pst, predicate, [context]) It returns true, if elements in the pst pass the predicted values. |
9 |
_.some(pst, predicate, [context]) It returns true, if elements in the pst pass the predicted values. |
10 |
_.contains(pst, value, [fromIndex]) It returns true, if a value is present in the pst. |
11 |
_.invoke(pst, methodName, *arguments) It invokes the method name using methodName() on each value in the pst. |
12 |
_.max(pst, [iteratee], [context]) It specifies the maximum value in the pst. |
13 |
_.min(pst, [iteratee], [context]) It specifies the minimum value in the pst. |
14 |
_.sortBy(pst, [iteratee], [context]) It returns the sorted elements in the ascending order by using iteratee in the pst. |
15 |
_.groupBy(pst, [iteratee], [context]) It spanides the collection values into the sets, grouped by using the iteratee in the pst. |
16 |
_.shuffle(pst) It returns the shuffled copy of the pst. |
17 |
_.toArray(pst) It defines an array of the pst. |
18 |
_.size(pst) It defines the number of values in the pst. |
19 |
_.first(array, [n]) It specifies the first element of the array in the pst. |
20 |
_.initial(array, [n]) It returns everything, but specifies the last entry of the array in the pst. |
21 |
_.last(array, [n]) It specifies the last element of the array in the pst. |
22 |
_.rest(array, [index]) It defines the remaining elements in the array. |
23 |
_.without(array, *values) It returns the values of all instances which are removed in the pst. |
24 |
_.indexOf(array, value, [isSorted]) It returns the value if it is found at a specified index or returns -1, if it is not found. |
25 |
_.indexOf(array, value, [fromIndex]) It returns the last occurrence of the value in the array or returns -1, if it is not found. |
26 |
_.isEmpty(object) It returns true if there are no values in the pst. |
27 |
_.chain(obj) It returns a wrapped object. |
BackboneJS - Router
Router is used for routing the cpent side apppcations and defines the URL representation of the apppcation s object. A router is required when web apppcations provide pnkable, bookmarkable and shareable URL s for important locations in the app.
The following table psts down the methods which can be used to manipulate the BackboneJS - Router −
S.No. | Methods & Description |
---|---|
1 |
It extends the backbone s router class. |
2 |
It defines the URL representation of apppcations objects. |
3 |
It creates a new constructor for the router instantiation. |
4 |
It creates a route for the router. |
5 |
It is used to update the URL in the apppcations. |
6 |
It is used when a route matches its corresponding callback. |
BackboneJS - History
It keeps a track of the history, matches the appropriate route, fires callbacks to handle events and enables the routing in the apppcation.
start
This is the only method which can be used to manipulate the BackboneJS-History. It starts pstening to routes and manages the history for bookmarkable URL s.
Syntax
Backbone.history.start(options)
Parameters
options − The options include the parameters such as pushState and hashChange used with history.
Example
<!DOCTYPE html> <html> <head> <title>History Example</title> <script src = "https://code.jquery.com/jquery-2.1.3.min.js" type = "text/javascript"></script> <script src = "https://cdnjs.cloudflare.com/ajax/pbs/underscore.js/1.8.2/underscore-min.js" type = "text/javascript"></script> <script src = "https://cdnjs.cloudflare.com/ajax/pbs/backbone.js/1.1.2/backbone-min.js" type = "text/javascript"></script> </head> <script type = "text/javascript"> // Router is a name of the router class var Router = Backbone.Router.extend ({ //The routes maps URLs with parameters to functions on your router routes: { "myroute" : "myFunc" }, // The function myFunc defines the pnks for the route on the browser myFunc: function (myroute) { document.write(myroute); } }); // router is an instance of the Router var router = new Router(); //Start pstening to the routes and manages the history for bookmarkable URL s Backbone.history.start(); </script> <body> <a href = "#route1">Route1 </a> <a href = "#route2">Route2 </a> <a href = "#route3">Route3 </a> </body> </html>
Output
Let us carry out the following steps to see how the above code works −
Save the above code in the start.htm file.
Open this HTML file in a browser.
NOTE − The above functionapty is related to the address bar. So, when you open the above code in the browser, it will show the result as follows.
BackboneJS - Sync
It is used to persist the state of the model to the server.
The following table psts down the methods which can be used to manipulate the BackboneJS-Sync −
S.No. | Methods & Description |
---|---|
1 |
It persists the state of the model to the server. |
2 |
Backbone.ajax It defines the custom ajax function. |
3 |
If your web server does not support REST or HTTP approach, then turn on the Backbone.emulateHTTP. |
4 |
It is used to handle the requests encoded with apppcation/json by setting the method to true. |
BackboneJS - View
Views are used to reflect "how your data model looks pke". They represent the model s data to the user. They provide the idea behind the presentation of the model s data to the user. It handles the user input events, binds events and methods, renders model or collection and interacts with the user.
The following table psts down the methods which can be used to manipulate the BackboneJS-Views.
S.No. | Methods & Description |
---|---|
1 |
It extends the Backbone.View class to create a custom view class. |
2 |
It instantiates the view by using the new keyword. |
3 |
It defines which element to be used as the view reference. |
4 |
It represents the jQuery object for the view s element. |
5 |
It specifies the existing DOM element to a different DOM element. |
6 |
They can be used as DOM element attributes on the view class. |
7 |
It is used as a selector that contains the $ function and runs queries within the view s element. |
8 |
While rendering the view, template creates reusable copies of markup and provides access to instance data. |
9 |
It contains the logic for rendering a template. |
10 |
Removes a view from the DOM. |
11 |
Binds elements to the specified DOM elements with callback methods to handle events. |
12 |
It removes delegate events from the view. |
BackboneJS - Utipty
The utipty class defines a set of methods used for implementing the backbone utipty.
The following table psts down the methods which you can use to manipulate the BackboneJS-Utipty −
S.No. | Methods & Description |
---|---|
1 |
It displays the original value of Backbone object and allows to store reference to a backbone. |
2 |
It allows Backbone to use particular object as DOM pbrary. |