我对backbone.js很新,并且正在学习本教程,以获取点击元素Site的模型的正确方法。但是,当我单击一个元素时,警报将触发所有div。我知道事件必须附加到所有div,并且由div的点击触发,如果我将ID附加到每个div,我可以绕过这个,但是根据教程,这不是正确的方法它。这是教程Link
的JSFiddle和我的代码(script.js)
var Item = Backbone.Model.extend
({
defaults:
{
price:35,
photo: "images/flower1.jpg"
}
});
var Cart = Backbone.Collection.extend
({
model: Item
});
var items = [
{ id: 1, title: "Macbook Air", price: 799 },
{ id: 2, title: "Macbook Pro", price: 999 },
{ id: 3, title: "The new iPad", price: 399 },
{ id: 4, title: "Magic Mouse", price: 50 },
{ id: 5, title: "Cinema Display", price: 799 }
];
var cartCollection = new Cart(items);
var ItemView = Backbone.View.extend
({
tagName: "div",
className: 'item-wrap',
template: $("#itemTemplate").html(),
render: function()
{
var templ = _.template(this.template);
$(this.el).html(templ(this.model.toJSON()));
return this;
}
})
var CartCollectionView = Backbone.View.extend
({
el: $("#yourcart"),
initialize: function()
{
this.collection = cartCollection;
this.collection.bind('onclick', function(item)
{
alert('Item has been clicked');
});
this.render();
},
events:
{
"click div": "clicked"
},
clicked: function(e)
{
e.preventDefault();
var id = $(e.currentTarget).data("id");
console.log(id);
var item = this.collection.get(id);
console.log(item);
var title = item.get("title");
console.info("Showing title "+title);
//alert(title);
},
render: function()
{
this.collection.each(function(item)
{
this.renderItem(item);
}, this);
},
renderItem: function(item)
{
var itemView = new ItemView({ model:item});
$(this.el).append(itemView.render().el);
}
});
$(document).ready(function() {
console.info('Doc ready');
var cart = new CartCollectionView();
});
和html(index.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Shopping Cart
</title>
<link rel="stylesheet" href="lib/style.css" type="text/css">
</head>
<body>
<span id="yourcart"></span>
<script id="itemTemplate" type="text/template">
<img src="<%= photo %>" alt="<%= title %>">
<div id="test" data-id="<%= id %>">
<h2><%= title %></h2>
<h4>£<%= price %></h4>
</div>
</script>
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="lib/underscore.js" type="text/javascript"></script>
<script src="lib/backbone.js" type="text/javascript"></script>
<script src="lib/script.js" type="text/javascript"></script>
</body>
</html>
答案 0 :(得分:1)
正常工作要求每个视图只有一个<div>
。在您的示例中,特定itewm的事件处理程序应在ItemView
中注册,而不是CartView
。