What Is Backbone.js?
Backbone.js is a JavaScript client-side (front-end) framework that helps to organize your code and makes it easier for you to develop single-page web applications.
Using Backbone, the JavaScript is better organized, structured, where the logic (the data-model-and the presentation) is sufficiently decoupled.
Why We Need Backbone.js
- You will build JS applications considerably faster than you ever have.
- IT supports MVC design.
- Major front-end JavaScript frameworks (Backbone.js, Derby.js, Meteor.js, Knockout.js, Ember.js, Angular.js, and Spine.js). Backbone.js is a proven JS framework.
Code Sample To Work On BackBone.JS
I have created a sample to clear the basic concept of Backbone.Js. To access the Backbone libraries, I have used online http://cdnjs.cloudflare.com for Ajax libraries.
For this we only need to create two files, sampleTask.js and sampleTask.html.
The sampleTask.html would look like this:
<!DOCTYPE html >
<html>
<head>
<title>Backbone.js Sample by Dev</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script type="text/javascript" src="sampleTask.js"></script>
</head>
<body>
<input type="text" placeholder="Add The Tasks" id="input" />
<button id="add-input">Add Task</button>
<ul id="task-list"></ul>
</body>
</html>
Another sampleTask.js file needs to have the following set of code.
Add the code and execute the HTML file. The HTML file already has the reference of the following created JS file "sampleTask.js".
$(function() {
TaskList = Backbone.Collection.extend({
initialize: function() {
}
});
TaskView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getTask'
},
initialize: function() {
var thisView = this;
this.tasklist = new TaskList;
_.bindAll(this, 'render');
this.tasklist.bind("add", function(model) {
thisView.render(model);
})
},
getTask: function() {
var task_name = $('#input').val();
this.tasklist.add({ name: task_name });
},
render: function(model) {
$("#task-list").append("<li>" + model.get("name") + "</li>");
console.log('rendered')
}
});
var view = new TaskView({ el: 'body' });
});
Code Explanation
In the preceding JS code, initially I have created a TaskList collection to add the items.
In the initialize method, the view registers itself for two built-in model collection events: add and remove. I have added the add event to render the view corresponding to the added TaskList model.
The "getTask" method is used to get the value from any input type and add that in the preceding declared TaskList collection.
The last "render" method would be called to display the List (Added items as model) in the HTML element "task-list".
Code Output