Introduction
In this article I will show you how to bind DOM events with the View method in backbone.js. At the time of writing, to use backbone.js we need to add three dependencies, the first is the "jQuery" library, the second is the "Underscore.js" library and the last is the Backbone.js library. This associates the click event to the button on the DOM.
In this article you can see that when we click on the button then one item is added to the list. It will be done an infinite number of times. Here DOM events are bound to the View method. In the backbone, there is no separate controller to handle this type of binding, here every event happens in the View.
Now see the example:
- First create an application for using this binding.
- Start Visual Studio 2013.
- From the Start window select "New Project".
- Select "Installed" -> "Template" -> "Visual C#" -> "Web" -> "Visual Studio 2012" and select "ASP.NET Empty Web Application".
- Click on the "OK" button.
- Now Add an HTML page in the project:
- In the Solution Explorer.
- Right-click on the project and select "Add" -> "HTML Page".
- Change the name of the page.
- Click on the "Add" button.
Write this code:
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8">
<title>Add List Item</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<script src="AddList.js" type="text/javascript"></script>
</body>
</html>
- Now add the scripting file to the project:
- In the Solution Explorer.
- Right-click on the project then select "Add" -> "New Item" -> "JavaScript".
- Click on the "Add" button.
Add the following code in the scripting file:
(function($){
var ListView = Backbone.View.extend({
el: $('body'),
events: {
'click button#add': 'addItem'
},
initialize: function(){
_.bindAll(this, 'render', 'addItem');
this.counter = 0;
this.render();
},
render: function(){
$(this.el).append("<button id='add'>Click To Add List</button>");
$(this.el).append("<ul></ul>");
},
addItem: function(){
this.counter++;
$('ul', this.el).append("<li>Welcome"+this.counter+"</li>");
}
});
var listView = new ListView();
})(jQuery);
In the code above are the functions render() and addItem().
The render() function specifies to the button to add the new item in the list.
The addItem() method is called when you click on the button.
- Now set the HTML page as Execute, first by setting the property using "Set as start project".
- Right-click on the "AddListItem.html".
- Then select "Set as start page".
- Execute the application, this is displayed as a button:
When the button is clicked the new item will be added to the list.