Real Time Backbone.js Interview Questions and Answers PDF
• Explain What Is Backbone.js?
Backbone.js is a JavaScript client-side (front end) framework, which helps to organize your code and makes it easier to develop single page applications. It allows you to structure JavaScript code in an MVC (Model, View , Controller) fashion.
Model: It is a part of your code that populates and retrieves the data.
View: It is the HTML representation of this model.
Controller: It enables you to save your javascript application via a hashbang URl.
• What Are The Main Components Of Backbone.js ?
The main component of Backbone.js are:
1. Model
2. View
3. Collection
4. Router
5. Event class object
• Explain What Is Backbone.js Collections?
An ordered set of models are represented by Backbone.js collections. Any event in model will trigger an event in collection directly. For example, you can bind “change” event to be notified in a case when any model in the collection has been modified.
• Explain What Is Backbone.js Router Is Used For?
When ever an application want to change their URL fragment in order to provide bookmarkable and shareable URLs for an Ajax heavy application, backbone.js router is used.
• What Is Backbone Events?
Backbone events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events are not declared before they are bound to any object . Events reflects the state of the model.
• What Are The Keypoints Of Backbone?
1. It has hard dependency with underscore.js to make it more functional and supporting a range of useful collection based operations With jQuery it has a soft dependency
2. When the model changes it can update the HTML of your application automatically
3. It uses client-side rendering framework or Javascript templating to render html which avoid you to embed HTML code inside JavaScript code.
4. For UI updates and DOM manipulations if offers a significantly clean and elegant way.
• Why You Have To Use Backbone ? Advantages?
o By using JavaScript with the minimal set of data-structuring ( models & collections) and user interface (views & URLs) it enables you to develop a web application
o Backbone is best useful to develop 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
o Provides key value binding and custom events
o API with tons of functions
o Robust event handling
o API connetion over a RESTful JSON interface
• What Are The Three Js Files That You Require To Setup A Working Environment For Backbone?
you are required following three js files to setup a working environment for backbone
o jQuery
o Backbone
o Underscore
In your application put these files within js folder and use it in your index.html page
• Explain When You Require Backbone.js?
Backbone.js is required in following condition:
0. When developing a web application that requires a lot of JavaScript
1. It is required when you want to give structure to your code, if your application needs to be scalable.
2. Backbone is useful when a web application has to work with jQuery to traverse the DOM or give animations.
• Explain What Is View In Backbone.js?
Backbone view is a Javascript object that manages a specific DOM element and descendants.
0. Views are not HTML
1. It is a description of a model
2. The HTML code comes from templates
3. Works with any template system
• Explain What Is Backbone.js Models?
Backbone.js models are object and core of backbone.js. It contains an array of attributes and listens for events. To represent your data, Backbone provides a model object. For example, you have a to do list, you would have a model representing each item on that list.
• Explain How You Can Use Backbone.js For Multiple Page Web App?
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 http://wisdomjobs.com/* will serve /var/www/wisdomjobs.com/index.html. 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.
• Explain What Is Modelbinder In Backbone.js ?
To make synchronization process of views and models together, ModelBinder class is used.
• What Is The Most Powerful Capabilities Of The Modelbinder ?
The most powerful capabilities of ModelBinder class is that it enables you to define scope when you create your bindings using jQuery.
0. If your views are simple, you can rely on default scoping rules that are based off of the html “name” attribute.
1. You can define scoping with jQuery selectors if your views are complex.
• Explain What Is Converter In Backbone.js?
A function is called when model’s attribute is copied to an html element or when an html element value is copied into a model’s attribute, this function is referred as Converter in Backbone.js
• What Is Model.attributes?
The attributes property is the internal hash containing the model’s state, usually a form of the JSON object representing the model data on the server. It is often a straightforward serialization of a row from the database.
• What Is The Function Of Tojson?
It returns a shallow copy of the model’s attribute for JSON stringification. This function is used for persistence, serialization and for augmentation before being sent to the server. This does not return a JSON string.
• Explain When You Can Use Unbinding Function In Backbone.js?
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]
• What Are The Configuration Options Available?
The configuration options available are:
0. InitialCopyDirection
1. modelSetOptions
2. change Triggers
3. boundAttribute
4. suppressThrows
5. converter
• Mention What Are The Typical Problems You Might Face With The Backbone View Code?
o Application models don’t change very often
o Application pages are frequently refreshed from scratch from the server
o Between different view models are not shared
• What Is The Function Of Escape?
It gets the current value of an attribute from the model but returns the HTML-escaped version of a model’s attribute. It is helpful in preventing XSS attacks, if you are interpolating data from the model into HTML.
• Explain What Is The Function Of Parse?
When ever a model’s data is returned by the server, in fetch and save , this data is called parse. It is called by Backbone whenever a collection’s models are returned by server, in fetch.
• What Is Backbone.sync Is Used For?
When Backbone wants to save or read a model to the server it calls out a function called as Backbone.sync.
• In Backbone View, What Is The Use Of Setelement?
setElement function is used when Backbone view has to be applied to a different DOM element.
• Explain What Is Model.cid?
Model.cid works as a unique identifier. It is a special property of models, the cid or client id is automatically assigned to all models when they are first created. This property is useful when the model is not saved to the server, but needs to be visible in the UI. It takes the from c1,c2….
• What Is Backbone.js? How Does It Help Developers?
BackboneJs is a JavaScript framework which allows the developers to make their life easier by providing the below features:
Model:– Store data
Model can have listeners bound to them to detect changes to their values
Collection: Group of models
View: Represents UI
Routing: Manages how to show appropriate view when request through URL
• What Is Models In Backbone.js?
Models are used to represent data from your server. Model in BackboneJs contains:
o Interactive data
o Business Logic
o Conversions
o Validations
o Computed properties
o Access control
MyClass = Backbone.Model.extend({
initialize: function(){
alert("I will initialize the model when it is created. I am like constructor.");
}
});
var myObj = new MyClass();
• How Can You Set Attributes Of A Model?
You can set attributes of a model in two ways. Using constructor parameter or .set().
See the below example:
var myObj = new MyClass({ attrib1: "Thomas", attrib2: 67});
//Or we can set afterwards, these operations are equivalent
var myObj = new MyClass();
myObj.set({ attrib1: "Thomas", attrib2: 67});
• How Can You Get The Attribute Value Of A Model?
You can get the value of model attribute by using .get() method.
See the example below:
//Set attributes
var obj = new MyClass({ attrib1: "Attribute1", attrib2: 50});
//Get attributes
var attrib1 = obj.get("name"); // "Attribute1"
var attrib2 = obj.get("age"); // 50
• Can You Have Default Values For Model? If Yes, How?
Yes, we can set default values for the model attributes.
See the example below:
MyClass = Backbone.Model.extend({
defaults: { //sets default values
attrib1: 'Default Attribute1 Value',
attrib2: 0
},
initialize: function(){
alert("It is so easy to set default values. Isn't it?");
}
});
• How Can You Write The Business Logic In Model?
We can write the methods which contain the business logic.
See the example below:
Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0,
child: ''
},
initialize: function(){
alert("This class has adop() method which contains business logic to set new child.");
},
adopt: function( newChildsName ){
this.set({ child: newChildsName });
}
});
var person = new Person({ name: "Thomas", age: 67, child: 'Ryan'});
person.adopt('John Resig');
var child = person.get("child"); // 'John Resig'
• How Can You Track Any Change In Model Attribute Value?
All attributes of a model can have listeners bound to them to detect changes to their values. In our initialize function, we are going to bind a function call everytime we change the value of our attribute. In this case, if the name of our “person” changes, we will alert their new name. Syntax for attaching callback to change event of attribute is this.on(“change”, function(model){});.
See the example below:
Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0
},
initialize: function(){
alert("Below we are attaching callback to change event of 'name' attribute");
this.on("change:name", function(model){
var name = model.get("name"); // 'Stewie Griffin'
alert("Changed my name to " + name );
});
}
});
var person = new Person({ name: "Thomas", age: 67});
person.set({name: 'Stewie Griffin'}); // This triggers a change and will alert()
• How The Actions Performed On Model Is Translated To Restful Operations? Give An Example.?
Models are used to represent data from your server and actions you perform on them will be translated to RESTful operations. The id attribute of a model identifies how to find it on the database usually mapping to the surrogate key.
Suppose you have a table Users with columns id, name, email and you want to save the model back on server when user clicks save button. If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server. For this,
see the example below:
var UserModel = Backbone.Model.extend({
urlRoot: '/user', //RESTful API relative path
defaults: {
name: '',
email: ''
}
});
var user = new UserModel();
// Notice that we haven't set an `id`. In case of update operation, we need to pass 'id' as well.
var userDetails = {
name: 'Thomas',
email: 'youemailid@domain.com'
};
// Because we have not set a `id` the server will call
// POST /user with a payload of {name:'Thomas', email: 'youremailid@domain.com'}
// The server should save the data and return a response containing the new `id`
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
})
• How Backbone Decides If It Should Use Post/get/ Request To The Server? What Are The Methods Backbone Has Reserved For These Operations?
If we instantiate a model with an id, Backbone.js will automatically perform a GET request to the urlRoot + ‘/id’ using fetch() method. (conforming to RESTful conventions)
If the id attribute of the model is null, Backbone.js will send a POST request to the urlRoot of the server using save() method.
If the id attribute of the model is not null, Backbone.js will send a PUT request instead of a POST request using save() method.
If a model has an id we know that it exists on the server, so if we wish to remove it from the server we can call destroy() method. destroy will fire off a DELETE /user/id (conforming to RESTful conventions).
See the example below for all these above operations:
// Here we have set only the `id` of the model so it will call fetch() method.
var user = new Usermodel({id: 1});
// The fetch below will perform GET /user/1
// The server should return the id, name and email from the database
user.fetch({
success: function (user) {
alert(user.toJSON());
}
})
// Here we have set all the attributes, along with id,
// of the model so it will call save() method with PUT
var user = new Usermodel({
id: 1,
name: 'Thomas',
email: 'myemailid@domain.com'
});
// Let's change the name and update the server
// Because there is `id` present, Backbone.js will fire
// PUT /user/1 with a payload of `{name: 'Davis', email: 'myemailid@domain.com'}`
user.save({name: 'Davis'}, {
success: function (model) {
alert(user.toJSON());
}
});
// Here we have set all the properties of model.
var user = new Usermodel({
id: 1,
name: 'Thomas',
email: 'thomasalwyndavis@gmail.com'
});
// Because there is `id` present, Backbone.js will fire
// DELETE /user/1
user.destroy({
success: function () {
alert('Destroyed');
}
});
• What Are The Tips/tricks/practice, With Respect To Model, You Follow?
Below are some practices you should follow while working with Backbone models:
Get all the Current Attributes
obj.attributes gives a direct reference to the attributes and you should be careful when playing with it. Best practice would suggest that you use .set() to edit attributes of a model to take advantage of backbone listeners.
var person = new Person({ name: "Thomas", age: 67});
var attributes = person.toJSON(); // { name: "Thomas", age: 67}
/* This simply returns a copy of the current attributes. */
var attributes = person.attributes;
Validate Data Before You Set or Save It
Always implement validate() method so that Backbone validates the input before setting any attribute value. It ensures that invalid data is not stored on your server.
Person = Backbone.Model.extend({
// If you return a string from the validate function,Backbone will throw an error
validate: function( attributes ){
if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){
return "You can't be negative years old";
}
},
initialize: function(){
//Bind callback for error event
this.bind("error", function(model, error){
// We have received an error, log it, alert it or forget it <img alt=":)" class="wp-smiley" src="http://synvistech.com/blogs/wp-includes/images/smilies/simple-smile.png" style="height: 1em; max-height: 1em;" />
alert( error );
});
}
});
var person = new Person;
person.set({ name: "Mary Poppins", age: -1 });
// Will trigger an alert outputting the error
var person = new Person;
person.set({ name: "Dr Manhatten", age: -1 });
• What Is View In Backbone.js?
0. Reflect what your applications’ data models look like.
1. Used to listen to events and react accordingly.
• How Do You Define View In Backbone.js?
You can define views in Backbone.js similar to Backbone models. See example below:
SearchView = Backbone.View.extend({
initialize: function(){
alert("WOW! SearchView has been defined.");
}
});
// The initialize function is always called when instantiating a Backbone View.
// Consider it the constructor of the class.
var search_view = new SearchView();
//You can specify el property for the view or else it will create empty div and assign it
<div id="search_container"></div>
var search_view = new SearchView({ el: $("#search_container") });
• What Is “el” Property Of Backbone.js View?
The “el” property references the DOM object created in the browser. Every Backbone.js view has an “el” property, and if it is not defined, Backbone.js will construct its own, which is an empty div element.
• How Can You Use Underscore Templates In Backbone.js Views?
0. First, create an underscore template
1. Create div for el property of the view
2. Compile the template using underscore
3. Load the compiled HTML into Backbone “el”
See the below example:
<script type="text/template" id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
// Compile the template using underscore
var template = _.template( $("#search_template").html(), {} );
// Load the compiled HTML into the Backbone "el"
this.$el.html( template );
}
});
var search_view = new SearchView({ el: $("#search_container") });
</script>
• How Can You Attach Listeners To Events In A View?
Use the “events” attribute of Backbone.View. Remember that event listeners can only be attached to child elements of the “el” property.
See example below:
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var template = _.template( $("#search_template").html(), {} );
this.$el.html( template );
},
//Attach listener to click event of the search button
events: {
"click input[type=button]": "doSearch"
},
doSearch: function( event ){
// Button clicked, you can access the element that was clicked with event.currentTarget
alert( "Search for " + $("#search_input").val() );
}
});
• How Can You Use Template Variables?
You can access template variables with <%= %>.
<script type="text/template" id="search_template">
<label><%= search_label %></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
<script type="text/javascript">
SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
//Pass variables in using Underscore.js Template
var variables = { search_label: "My Search" };
// Compile the template using underscore
var template = _.template( $("#search_template").html(), variables );
// Load the compiled HTML into the Backbone "el"
this.$el.html( template );
},
events: {
"click input[type=button]": "doSearch"
},
doSearch: function( event ){
// Button clicked, you can access the element that was clicked with event.currentTarget
alert( "Search for " + $("#search_input").val() );
}
});
var search_view = new SearchView({ el: $("#search_container") });
</script>
• What Is Router In Backbone.js?
Backbone routers are used for routing your applications URLs when using hash tags(#). In the traditional MVC sense, they don’t necessarily fit the semantics and if you have read “What is a view?” it will elaborate on this point. Though a Backbone “router” is still very useful for any application/feature that needs URL routing/history capabilities.
Defined routers should always contain at least one route and a function to map the particular route to.
Routes interpret anything after “#” tag in the URL. All links in your application should target “#/action” or “#action”. (Appending a forward slash after the hashtag looks a bit nicer, e.g. http://wisdomjobs.com/#/user/help).
<script>
var AppRouter = Backbone.Router.extend({
routes: {
"*actions": "defaultRoute" // matches http://wisdomjobs.com/#anything-here
}
});
// Initiate the router
var app_router = new AppRouter;
app_router.on('route:defaultRoute', function(actions) {
alert(actions);
})
// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start();
</script>
• What Is Dynamic Routing?
In case of Dynamic Routing, you can use variables in the route. For example, you might want to retrieve a post with a variable id with a friendly URL string. You can specify variable name in the route as :variablename in dynamic routing.
<script>
var AppRouter = Backbone.Router.extend({
routes: {
"posts/:id": "getPost",
"*actions": "defaultRoute" // Backbone will try to match the route above first
}
});
// Instantiate the router
var app_router = new AppRouter;
app_router.on('route:getPost', function (id) {
// Note the variable in the route definition being passed in here
alert( "Get post number " + id );
});
app_router.on('route:defaultRoute', function (actions) {
alert( actions );
});
// Start Backbone history a necessary step for bookmarkable URL's
Backbone.history.start();
</script>
• What Are “:params” And “*splats” In Dynamic Routing?
Backbone uses two styles of variables when implementing routes:
0. “:params” match any URL components between slashes. You can specify single fragment using “.params”
1. “*splats” match any number of URL fragments after the query.
2. Note that due to the nature of a “*splat”, it will always be the last variable in your URL as it will match any and all components.
3. “*splats” or “:params” in route definitions are passed as arguments (in respective order) to the associated function.
4. A route defined as “/:route/:action” will pass 2 variables (“route” and “action”) to the callback function.
• What Is Collection In Backbone.js?
Backbone collections are simply an ordered set of models.
Typically, your collection will only use one type of model but models themselves are not limited to a type of collection.
var Song = Backbone.Model.extend({
initialize: function(){
console.log("Music is the answer");
}
});
var Album = Backbone.Collection.extend({
model: Song
});
• Can You Give An Example Of How To Build A Collection?
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function(){
console.log("Music is the answer");
}
});
var Album = Backbone.Collection.extend({
model: Song
});
var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });
var myAlbum = new Album([ song1, song2, song3]);
console.log( myAlbum.models ); // [song1, song2, song3]
No comments:
Post a Comment