我试图根据我看到的教程使用BackboneJS Events点击的链接添加和删除一个类,但我不确定为什么我的代码无效。
如果点击了该链接,请向其添加“已选择”类,并从可能拥有它的任何其他链接中删除“已选择”类。
我不确定为什么事件没有解雇。这是一个小提琴:http://jsfiddle.net/EL8gM/
这是JavaScript:
var Model = Backbone.Model.extend({
defaults: {
items: [
{
"name": "One",
"id": 1
},
{
"name": "Two",
"id": 2
},
{
"name": "Three",
"id": 3
}
]
}
});
var myModel = new Model();
var View = Backbone.View.extend({
el: '.js-container',
initialize: function(options) {
// Re-render when the model changes
this.model.on('change:items', this.render, this);
},
template: _.template($('#list-template').html()),
events: {
"#items li a": "this.setSelectedItem"
},
render: function() {
console.log(this.model.toJSON());
this.$el.html(this.template(this.model.toJSON()));
},
setSelectedItem: function(event) {
var selectedItem = $(event.currentTarget);
console.log('selectedItem =', selectedItem)
// Set all of the items to not have the selected class
$('#items li a').removeClass('selected');
selectedItem.addClass('selected');
// Store a reference to what item was selected
this.selectedItemId = selectedItem.data('id');
return false;
}
});
var myView = new View({model: myModel});
myView.render();
这是我的HTML
<script id="list-template" type="template">
<ul id="items">
<% for(i = items.length - 1; i >= 0; i--) { %>
<li>
<a href="#" data-id="<%= items[i].id %>"><%= items[i].name %></a>
</li>
<% } %>
</ul>
</script>
<div class="js-container"></div>
答案 0 :(得分:1)
应该是
events: {
"click #items li a": "setSelectedItem"
},
编辑:还有另一个拼写错误的控制台错误
cosnole.log('selectedItem =', selectedItem)