Massimiliano Marini
Massimiliano Marini

Reputation: 499

backbone.js doesn't fire click event on DOM element

I can't fire the click event on DOM element.

This is my js file: app.js. I'm pretty sure I'm missing something or doing wrong here but I can't figured out where.

var App = Backbone.View.extend({

    el: $('body'),

    initialize: function() {
        _.bindAll(this, 'sayHello');
    },

    events: {
        'click .link': 'sayHello'
    },

    sayHello: function(e) {
        alert('Hello!');
    }

});

var app = new App();

and this is my HTML file: index.htm.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>

    <script type="text/javascript" src="assets/js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="assets/js/underscore-min.js"></script>
    <script type="text/javascript" src="assets/js/backbone-min.js"></script>

    <script type="text/javascript" src="assets/js/app.js"></script>

</head>
<body>

<a href="#" class="link">Click here!</a>

</body>
</html>

Upvotes: 1

Views: 1564

Answers (2)

Andrey Kuzmin
Andrey Kuzmin

Reputation: 4479

You have to initialize your view on dom load event.

var App = Backbone.View.extend({

    initialize: function() {
        _.bindAll(this, 'sayHello'); // you don't need this for your code to work
    },

    events: {
        'click .link': 'sayHello'
    },

    sayHello: function(e) {
        alert('Hello!');
    }

});


$(function(){
  var app = new App({el: $("body")});
});

Upvotes: 0

Mauvis Ledford
Mauvis Ledford

Reputation: 42384

This was admittingly trickily. Think through the code logically. Your JS script is in your head.

The jQuery selector el: $('body') does not exist yet. (JavaScript executes immediately). Try doing el: 'body'.

Upvotes: 2

Related Questions