Flu*_*yte 1 collections undefined backbone.js
我写了以下内容,由于某种原因,当我尝试从集合中删除项目时,它返回未定义的removeItem函数中的项目:
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;
});
Run Code Online (Sandbox Code Playgroud)
模型没有remove方法(除非你自己添加了一个),所以这不起作用:
var thisitem = this.collection.get(thisid);
thisitem.remove(); // <------ this goes boom!
Run Code Online (Sandbox Code Playgroud)
模型确实有destroy方法,所以你可以:
thisitem.destroy();
Run Code Online (Sandbox Code Playgroud)
这将告诉服务器模型已消失"destroy",它触发的事件将通知集合模型已消失.如果您不想与服务器通信,那么您可以将集合告诉remove模型:
this.collection.remove(thisitem);
Run Code Online (Sandbox Code Playgroud)
这将在不打扰服务器的情况下将其从集合中删除.
切换到this.collection.remove工作:http://jsfiddle.net/ambiguous/8chHf/
我在这里的时候,你有一个隐藏的问题:
self = {};
Run Code Online (Sandbox Code Playgroud)
当您可能想要分配一个名为的局部变量时,您将分配给全局self(实际上是其标准属性window)self.这就足够了:
return {
start: function() {
new TodoView({collection: new TodoCollection()});
}
};
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做,如果你愿意:
var self = {};
self.start = function(){
new TodoView({collection: new TodoCollection()});
};
return self;
Run Code Online (Sandbox Code Playgroud)
我喜欢使用_this或that代替,self因为window.self如果你忘记了varin var self;或者如果你不小心忘记声明那么可能会导致有趣的错误self.是的,我很难学到这一点.
| 归档时间: |
|
| 查看次数: |
6405 次 |
| 最近记录: |