1

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>
4

2 回答 2

2

诚然,这很棘手。逻辑地思考代码。你的 JS 脚本在你的head.

jQuery 选择器el: $('body')还不存在。(JavaScript 立即执行)。尝试做el: 'body'

于 2012-12-01T00:40:07.993 回答
0

您必须在 dom 加载事件上初始化您的视图。

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")});
});
于 2012-12-01T14:58:51.977 回答