刪除項目我已經寫了以下內容,由於某種原因,當我試圖從它在removeItem
函數返回undefined該項目集合中刪除的項目:骨幹不能從收集
Todos = (function(){
//////////////////////////
//
// MODEL
//
//////////////////////////
var TodoModel = Backbone.Model.extend({
defaults: {
id: null,
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(item) {
var templ = _.template(this.template);
var id = _.uniqueId('todo_');
this.el.children('ul').append(templ({id: id,item: item}));
},
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) {
var thisid = this.$(e.currentTarget).parent('li').data("id");
var thisitem = this.collection.get(thisid);
thisitem.remove();
// Remove from DOM
$(e.target).parent('li')
.fadeOut(300,function() {
$(this).remove();
});
},
printCollection: function(){
this.collection.each(function(item) {
console.log(item.get('item'));
});
}
});
//////////////////////////
//
// SELF
//
//////////////////////////
self = {};
self.start = function(){
new TodoView({collection: new TodoCollection()});
};
return self;
});
你的模板是什麼樣的?你確定'thisid'是你期望的嗎?通常你'model.destroy()'不''model.remove()''thisitem.remove();'有點懷疑。 jsfiddle.net或jsbin.com上的功能示例會很有幫助。 –
@ muistooshort - 這是我的小提琴:http://jsfiddle.net/nYpqe/2/。看起來我根本無法抓住模型。我已經嘗試了一個點擊事件來提醒內容,即使這樣也行不通。 – Fluidbyte