我正在主干中创建非常知名的待办事项列表应用程序,但有一个功能不起作用,即 mycollection.add()
方法。
使用 todoItems.remove(todoItem.at(0))
删除项目时一切正常。
我遇到的问题是添加新项目时:
var newItem = new todoItem({ description: "cereal killer", status: "complete" });
todoItems.add(newItem)
--> 这不会将其添加到集合中,长度仍然相同。
我添加新项目的唯一方法是先删除一个项目,然后它会添加该项目,但它只能与一个项目一起使用。
有什么线索吗?
主要代码如下:
app.js
var TodoItem = Backbone.Model.extend({
defaults: {
description: "Pick up milk",
status: "incomplete",
id: 1
},
toggleStatus: function(){
if(this.get('status') === 'incomplete'){
this.set({'status': 'complete'});
} else {
this.set({'status': 'incomplete'});
}
this.save();
}
});
var TodoItems = Backbone.Collection.extend({
model: TodoItem,
localStorage: new Backbone.LocalStorage("choose-some-identifier"),
initialize: function () {
this.on('remove', this.hideModel, this);
},
hideModel: function (model) {
model.trigger('hide');
}
});
var TodosView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
render: function() {
this.addAll();
// this.collection.forEach(this.addOne, this);
return this;
},
addOne: function (todoItem) {
var todoView = new TodoView({ model: todoItem });
this.$el.append(todoView.render().$el);
},
addAll: function () {
this.collection.forEach(this.addOne, this);
}
});
var TodoView = Backbone.View.extend({
tagName: 'article',
id: 'todo-view',
className: 'todo',
template: _.template('<h3 class="<%= status %>">' +
'<input type=checkbox ' +
'<% if (status === "complete") print("checked") %> />' +
'<%= description %></h3>'),
events: {
"change input": "toggleStatus"
},
toggleStatus: function () {
this.model.toggleStatus();
},
remove: function(){
this.$el.remove();
},
initialize: function(){
this.render();
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
this.model.on('hide', this.remove, this);
},
render: function () {
var attributes = this.model.toJSON();
this.$el.html(this.template(attributes));
return this;
}
});
var todoItems = new TodoItems([
{
description: 'Jeffrey Way',
status: "incomplete"
},
{
description: 'John Doe',
status: "incomplete"
},
{
description: 'Sally Doe',
status: "incomplete"
}
]);
var todosView = new TodosView({ collection: todoItems});
$(document.body).append(todosView.render().el);
最佳答案
问题是这样的:
defaults: {
description: "Pick up milk",
status: "incomplete",
id: 1
}
您已将 id
设置为默认值。 id 应该是唯一的,您尝试添加另一个模型而不指定新的 id,因此 Backone 会注意到您已经有一个具有该 id 的模型,因此不会添加它。
解决方案:您不应该设置默认 ID,在本地创建模型时,正常过程是:
- 创建一个没有id的模型
- 在某个时刻.save
它
- 服务器响应所有属性+保存后的id
当然,获取服务器上已经存在的模型应该已经有一个 id。
PS,您不需要为单个集合(或获取)创建哈希:
this.set('status', 'complete');
PPS 在您看来,使用 listenTo
是个好主意:
this.listenTo(this.collection, 'add', ...);
这可以在某些情况下防止内存泄漏,并使批量停止监听事件变得更容易。
关于javascript - Backbone : adding new model to a collection is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125098/