3
votes
<!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

3

3 Answers

5
votes

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
});
2
votes

Your problem is that you are passing in el when you are defining your View class, instead of passing it in when you instantiate the View class. Try this instead:

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

// Pass in el when instantiating the view
new View({
    el: $("#listen_to_box")
});

See a working fiddle here.

0
votes
change to  
clicked: function (event) {
    console.log("events handler for " + this.$el.outerHTML);
}

see if it helps