Backbone view click checkbox listener

Karthic Rao picture Karthic Rao · Jul 29, 2013 · Viewed 16.1k times · Source
<!DOCTYPE HTML > 
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

        <script src="jquery.js">
    </script> 

    <script src="underscore.js">

    </script> 
    <script src="backbone.js">
    </script> 
    <script>
        var View = Backbone.View.extend({

            el: '#listen_to_box',

            events: { 
                'click [type="checkbox"]':'clicked',
            },
        clicked : function(event ) { 
            console.log("events handler for "+  this.el.outerHTML);
        }
    });

    </script>

    <div id="listen_to_box">
        <input type="checkbox" />
    </div>

</body>
</html>

The clicked function is not getting called when i click the checkbox , please help me out with associating a listener function for the click event on the checkbox . Thank you

Answer

Sushanth -- picture Sushanth -- · Jul 29, 2013

You code looks perfect. You have defined the Backbone View called View and the events are attached when try to create a new instance on the View.. So the event is never attached..

Just create a new instance and your code should work.

var view = new View(); or new View() should do

Check Fiddle

You code runs before the element is encountered on the page. To make it work you either need to move the code just before the closing tag or encase your code inside Document Ready handler

$(function() {
     // Your code here
});