I tried to use Backbone.js for one of my projects, but got a problem using view events.
The HTML file:
<html>
<head>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script type="text/javascript" src="model.js"></script>
</head>
<body>
<div id="app">
</div>
</body>
</html>
model.js code is
window.onload = function() {
var MyModel = Backbone.Model.extend({
defaults: {
name: "Test"
}
});
var MyView = Backbone.View.extend({
tagName: "li",
events: {
"click li": "Show"
},
render: function() {
this.el.innerHTML = this.model.get("name");
},
Show: function() {
alert(this.model.get("name"));
}
});
var model = new MyModel();
var view = new MyView({model: model});
view.render();
document.getElementById("app").appendChild(view.el);
}
I get no errors, but the “Show” function is not fired on “li” click. What is wrong?
The problem is you are binding the click event to the (non-existant) “li” child of the element, rather than the li element itself. Try this: