Backbone.js is a JavaScript client-side (front-end) framework that helps to organize the code by making it easier to develop single-page web application. It gives a structure to the web application by providing models with key-value binding and custom events; collections with a rich API of enumerable functions,views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.
Backbone Model
Models are the heart of any JavaScript application, containing the interactive data as well as a large part of logic surrounding it: conversions, validations, computed properties, and access control.
Let’s see how to create a model.
Person = Backbone.Model.extend({
initialize: function(){
alert(“Welcome to this world”);
}
});
var person = new Person;
initialize() is triggered whenever we create a new instance of a model.
Setting Attributes
If we want to pass some values while creating the instance, we may want to use the below format provided
Person = Backbone.Model.extend({
initialize: function(){
alert(“Welcome to this world”);
}
});
var person = new Person({ name: “Thomas”, age: 67});
//or we can set like this
var person = new Person();
person.set({ name: “Thomas”, age: 67});
Getting Attributes
If we want to get properties from model, we may want to use the model.get() method.
Person = Backbone.Model.extend({
initialize: function(){
alert(“Welcome to this world”);
}
});
var person = new Person({ name: “Thomas”, age: 67});
var age = person.get(“age”);//67
var name = person.get(“name”); //Thomas
If we want to set default values in the model, then we may want to use the property name “defaults” in the model declaration
Person = Backbone.Model.extend({
defaults:{
name : ‘John’,
age : 0
},
initialize: function(){
alert(“Welcome to this world”);
}
});
Manipulating Model Attributes
Models can contain as many custom methods to manipulate model attributes. By default, all methods are public.
Person = Backbone.Model.extend({
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’
Listening for changes
All attributes of a model can have listeners bound to them to detect changes in their values.
Person = Backbone.Model.extend({
initialize: function(){
alert(“Welcome to this world”);
this.on(“change:name”, function(model){
var name = model.get(“name”); // ‘John’
alert(“Changed my name to “ + name );
});
}
});
var person = new Person({ name: “Thomas”, age: 67});
person.set({name: ‘John’,});
In the above function, when the name of the person changes, it will alert the new value.
Interacting with server
Models are used to represent data from your server, and actions performed on them will be translated to RESTful operations.
The server has implemented a RESTful URL / user. Now our model definition looks like
var UserModel = Backbone.Model.extend({
urlRoot: ‘/user’,
});
Creating a model
If we need to create a new user on the server, then we can use the save method. If the attribute is null, Backbone will send a POST request to the urlRoot of the server.
var UserModel = Backbone.Model.extend({
urlRoot: ‘/user’
});
var user = new Usermodel();
// Notice that we haven’t set an `id`
var userDetails = {
name: ‘John’,
email: ‘Johndoe@gmail.com’
};
// Because we have not set a `id` the server will call
// POST /user with a payload of {name:’John’, email: ‘Johndoe@gmail.com’}
// The server should save the data and return a response containing the new `id`
user.save(userDetails, {
success: function (user) {
alert(user.toJSON());
}
});
Getting a Model
We can use fetch method to get the details from the server.If we instantiate an id, Backbone will automatically perform a GET request to the urlRoot+”/id”.
// Here we have set the `id` of the model
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());
}
});
Updating a model
We will use the save method here. If id parameter is present, Backbone will send a PUT request to the server.
// Here we have set the `id` of the model
var user = new Usermodel({
id: 1,
name: ‘Johndoe’,
email: ‘john@gmail.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: ‘John’, email: ‘john@gmail.com’}`
user.save({name: ‘John’}, {
success: function (model) {
alert(user.toJSON());
}
});
Deleting a model
If we want to delete an item from server, we can use the destroy method. It will send a Delete request to the server.
// Here we have set the `id` of the model
var user = new Usermodel({
id: 1,
name: ‘John’,
email: ‘john@gmail.com’
});
// Because there is `id` present, Backbone.js will fire
// DELETE /user/1
user.destroy({
success: function () {
alert(‘Destroyed’);
}
});
We can add validations to the model before saving the data.
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 ){
return “You can’t be negative years old”;
}
},
initialize: function(){
this.bind(“error”, function(model, error){
alert( error );
});
}
});
var person = new Person;
person.set({ name: “John”, age: –1 });
// Will trigger an alert outputting the error
Backbone View
Backbone views are used to reflect what your applications’ data model look like. They are also used to listen to events and react accordingly.
SearchView = Backbone.View.extend({
initialize: function(){
alert(“Alerts suck.”);
}
});
var search_view = new SearchView();
“el” property
The el property refers the DOM object created in the Browser. If it is not defined, Backbone will create an empty div element.
<div id=“search_container”></div >
<script type=“text/javascript”>
SearchView = Backbone.View.extend({
initialize: function(){
alert(“Alerts suck.”);
}
});
var search_view = new SearchView({ el: $(“#search_container”) });
</script>
Here, we set our el property to div#search_container.
Loading Template
Backbone.js is dependent on Underscore.js. We can implement a render() function which will load the template to the view’s el property.
<script “text/template” id=“search_template”>
</script>
<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>
Listening for Events
To attach a listener to our view, we use events attribute of Backbone.View.Listeners can be added to child elements of the “el” property. Let us attach a click listener.
Backbone Router
Backbone Routers are used for routing application’s URLs when using hash(#) tags. Defined routers contain at least one route and a function to map to that particular route. Routes interpret anything after # tags.
Backbone Collection
Backbone Collection is an ordered set of models. For example , if Todo Item is model , then Todo List can be Collection.
A generic Model/Collection Example
var Song = Backbone.Model.extend({
initialize: function(){
console.log(“Music is the answer”);
}
});
var Album = Backbone.Collection.extend({
model: Song
});
Lets populate the collection with data.
var Song = Backbone.Model.extend({
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]