Reputation: 511
My backbone.js app has a collection of items. The views for collection and each item render as expected.
Each item has a two actions on it, lets say A and B. How do I hook up event listeners in my ItemView class such that I can handle actions A and B?
window.SourceListItemView = Backbone.View.extend({ tagName: "li", initialize: function () { this.model.bind("change", this.render, this); this.model.bind("destroy", this.close, this); }, render: function () { $(this.el).html(this.template(this.model.toJSON())); return this; }, events: { "click .action_a": "doA", "click .action_b": "doB" }, doA: function(event) { alert("A clicked for " + JSON.stringify(event)); }, doB: function(event) { alert("B clicked for " + JSON.stringify(event)); }
});
ItemView's template
<a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;">
<h4><%= name %></h4>
<button class="btn btn-primary action_a"> A</button>
<button class="btn btn-info action_b"> B</button>
</a>
Upvotes: 0
Views: 154
Reputation: 376
This line seems to be the problem:
$(this.el).html(this.template(this.model.toJSON()));
I got it work using this:
this.$el.html(test(this.model.toJSON()));
Note I changed a number of other things to get it working locally which may or may not be further problems.
<a>
tag contains the buttons. Working code:
<html>
<script src="./jquery.js"></script>
<script src="./underscore.js"></script>
<script src="./backbone.js"></script>
<body>
</body>
<script>
window.SourceListItemView = Backbone.View.extend({
tagName: "li",
initialize: function () {
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
template: function(data) {
var compiled = _.template('<a href="#sources/<%=id %>" class="source thumbnail plain" style="text-align: center;"> <h4><%= name %></h4> </a> <button class="btn btn-primary action_a"> A</button> <button class="btn btn-info action_b"> B</button>');
return compiled;
},
render: function () {
var test = this.template();
this.$el.html(test(this.model.toJSON()));
return this;
},
events: {
"click .action_a": "doA",
"click .action_b": "doB"
},
doA: function(event) {
alert("A clicked for " + JSON.stringify(event));
},
doB: function(event) {
alert("B clicked for " + $(event.srcElement).html());
}
});
testModel = new Backbone.Model({id: 1, name: 'Elias'});
testRow = new SourceListItemView({model: testModel});
$('body').append(testRow.render().$el);
</script>
</html>
Upvotes: 1