我仍然试图从我的收藏中删除(销毁)模型。数据被分组并呈现为手风琴风格。但是当我在控制台中点击X时会注意到:
Uncaught Uncaught TypeError: Cannot call method 'destroy' of undefined
(function() {
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
window.vent = _.extend({}, Backbone.Events);
})();
//!models.js
App.Models.Item = Backbone.Model.extend({});
//!collections.js
App.Collections.Items = Backbone.Collection.extend({
model: App.Models.Item,
url: 'api/items.json'
});
//!views.js
App.Views.Items = Backbone.View.extend({
el: '#items',
events: {
'click .cccc':'deleteItem',
},
deleteItem: function() {
this.model.destroy();
},
initialize: function() {
this.listenTo( this.collection, "change", this.render );
this.template = _.template( document.getElementById('productsCategoriesTemlate').innerHTML );
this.render();
this.$el.accordion({ animate: 0 });
},
getGroups : function(){
return _.groupBy(this.collection.toJSON(), 'category');
},
render: function() {
this.el.innerHTML = this.template({ data : this.getGroups() });
},
addOne: function(item) {
// ????????????
}
});
App.Views.Item = Backbone.View.extend({
deleteItem: function() {
this.model.destroy();
},
// ???????????
});
//!router.js
App.Router = Backbone.Router.extend({
routes: {
'':'index',
},
index: function() {
console.log('index page !');
},
});
new App.Router;
Backbone.history.start();
App.items = new App.Collections.Items;
App.items.fetch().then(function() {
new App.Views.Items({ collection: App.items });
});
模板:
<script id="productsCategoriesTemlate" type="text/template">
<% _.each( data, function( category, i ){ %>
<h3 class="category-name"><%= i %></h3>
<div><% _.each( category, function( item ){ %>
<li class="product"><%= item.title %><p style="float:right;" class="cccc">X</p></li>
<% }) %>
</div>
<% }) %>
</script>
答案 0 :(得分:1)
您在哪里实例化Apps.Views.Items
?这是你的“收藏视图”吗?如果此视图代表您的集合,则必须以某种方式在'deleteItem'上传递或引用该模型。
App.Views.Items
不代表单个模型,因此this.model
不正确。
对于每个项目,您应该有一个单独的视图,例如App.Views.Item,并循环浏览并为App.Views.Items集合中的每个模型创建此视图。
App.Views.Items = Backbone.View.extend({
render: function() {
this.collection.each(function(model) {
var view = new App.Views.Item({ model: model });
this.$el.append(view.render().el);
});
},
});
App.Views.Item = Backbone.View.extend({
template: _.template($('#itemViewTemplate')),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
},
});
App.items = new App.Collections.Items;
App.items.fetch().then(function() {
var items = new App.Views.Items({ collection: App.items });
$('body').append(items.render().$el);
});
顺便说一句,一旦你掌握了Backbone以及它是如何工作的,你应该试试Marionette.js。它使所有这些事情变得更加简单。