Collections 从主干集合中删除项
我有以下代码。一切都很完美,但我正试图弄清楚如何从收藏中删除一件物品(注意:我是新来的)。我已经查看了其他几篇帖子,但我似乎能找到答案:Collections 从主干集合中删除项,collections,backbone.js,Collections,Backbone.js,我有以下代码。一切都很完美,但我正试图弄清楚如何从收藏中删除一件物品(注意:我是新来的)。我已经查看了其他几篇帖子,但我似乎能找到答案: Todos = (function(){ ////////////////////////// // // MODEL // ////////////////////////// var TodoModel = Backbone.Model.extend({ defaults: { item: null } });
Todos = (function(){
//////////////////////////
//
// MODEL
//
//////////////////////////
var TodoModel = Backbone.Model.extend({
defaults: {
item: null
}
});
//////////////////////////
//
// COLLECTION
//
//////////////////////////
var TodoCollection = Backbone.Collection.extend({
model: TodoModel
});
//////////////////////////
//
// VIEW
//
//////////////////////////
var TodoView = Backbone.View.extend({
el: $('#todos'),
itemField: $('#new-item'),
initialize: function(){
this.el = $(this.el);
},
events: {
'submit form': 'addItem',
'click .remove-item': 'removeItem',
// Debug
'click #print-collection': 'printCollection'
},
template: $('#item-template').html(),
render: function(i) {
var templ = _.template(this.template);
this.el.children('ul').append(templ({item: i}));
},
addItem: function(e) {
e.preventDefault();
item = this.itemField.val();
// Call render
this.render(item);
// Clear field
this.itemField
.val('')
.focus();
// Add to collection
var newItem = new TodoModel({
item: item
});
this.collection.add(newItem);
},
removeItem: function(e) {
$(e.target).parent('li')
.fadeOut(300,function() {
$(this).remove();
});
// NEED TO REMOVE FROM COLLECTION...
},
printCollection: function(){
this.collection.each(function(item) {
console.log(item.get('item'));
});
}
});
//////////////////////////
//
// SELF
//
//////////////////////////
self = {};
self.start = function(){
new TodoView({collection: new TodoCollection()});
};
return self;
});
可以使用主干的方法从集合中删除模型:
从集合中删除模型(或模型数组)。激发一个“移除”事件,您可以使用静默来抑制该事件。如果您是一个正在侦听“remove”事件的回调,则从集合中删除模型的索引将作为options.index提供
但是,如果您想这样做,您必须有一种方法来获取要从单击事件中删除的模型。基本上有两种方法可以做到这一点:
数据id
属性),以便事件处理程序可以在调用该id时获取该id,并使用该id获取模型(在本例中,将其从集合中移除)希望有帮助。传递给onRemove回调的数据是什么?@chovy:
(模型、集合、选项)
。有关所有内置事件的可靠回调引用,请参阅。