All about programming in GNU/LINUX

Backbone.js – Listening to DOM events using backbone.views

Writing Backbone.js applications requires three dependies , the Jquery Library , Underscore.js and Backbone.js libraries , this illustrates the simple task of associating a listener for the click event on the checkbox element on the DOM, Backbone.js provides all the necessary functionalities to make a fully fledge web applications , it is well known for the implementation of the MVc architecture , use Ctrl+shift+K in the firefox browser to open the Javascript console and view the console log

<!DOCTYPE HTML > 
<html>
<head>
	<meta charset="UTF-8">
	<title>Title</title>
</head>
<body>

	<script src="http://code.jquery.com/jquery-1.10.2.js">
	</script> 
	
	<script src="http://underscorejs.org/underscore-min.js">

	</script> 
	<script src="http://backbonejs.org/backbone-min.js">
	</script> 
	<script>
		$( document ).ready(function() {
		/*Enclose the script under Jquery Document.ready , this makes sure that the script is executed after the DOM 
		elements on the browser is loaded */
    		var View = Backbone.View.extend({

			el : '#listen_to_box' , 
			/*associate  DOM element on which you want to work on , 
			In this case #listen_to_box is the ID of the div element with the  checkbox */
			
			events: { 
				'click [type="checkbox"]':'clicked', 
				/*associate an event listener 'clicked' for 
				the click event on the checkbox , this is done using the Views events property*/
			},
		clicked : function(event ) { /*The Handler function for the click event on the checkbox*/
			console.log("events handler for "+  this.el.outerHTML);
			/* el.outerHTML has the markup or the HTML code of the DOM element associated with el, 
				in this case the 'div' element with the id of #listen_to_box is assigned to el */ 
		}
	});
	var view = new View();
			
});
					
	</script>
	
	<div id="listen_to_box">
		<input type="checkbox" />
	</div>

</body>
</html>


Js console

Js console

Advertisements

One response

  1. Hey There. I found your blog using msn. This is a very well written article.

    I’ll make sure to bookmark it and come back to read more of your useful info.
    Thanks for the post. I will certainly comeback.

    May 20, 2014 at 2:11 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s