这是我快速浏览您的代码的方法。我没有测试任何东西,所以可能有错别字。我仍然不确定杂散的空模型来自哪里,但是如果您按照如下所述重构您的应用程序,我怀疑问题会消失。
模型和集合看起来不错,所以让我们看看你的观点。
el: $('#todos'),
listBlock: $('#todos-list'),
newTodoField: $('#add input'),
//...
template: $('#todo-template').html(),
//...
events: { /* ... */ },
这些应该没问题,但是当您的视图“类”被加载时,您需要确保所有这些元素都在 DOM 中。通常你会编译一次模板:
template: _.template($('#todo-template').html()),
然后只是this.template用作函数来获取您的 HTML。我假设这template是一个编译的模板函数。
initialize: function () {
_this = this;
您在这里有一个意外的全局变量,这可能会导致有趣的错误。你想说var _this = this;。
this.el = $(this.el);
Backbone 已经为您提供了一个 jQuery 版本的elin,$el因此您不需要这样做,只需使用this.$el.
this.collection.fetch({
success : function(collection, response) {
_.each(response, function(i) {
var todo = new TodosModel({ /* ... */ });
// Add to collection
_this.collection.add(todo);
// Render
_this.render(todo);
});
},
//...
集合fetch将在调用处理程序之前将模型添加到集合中,success因此您不必创建新模型或向集合中添加任何内容。通常,该render方法渲染整个事物而不是仅渲染一个部分,并且您将视图绑定render到集合的"reset"事件;该fetch调用将在获取时触发一个"reset"事件,因此通常的模式如下所示:
initialize: function() {
// So we don't have to worry about the context. Do this before you
// use `render` or you'll have reference problems.
_.bindAll(this, 'render');
// Trigger a call to render when the collection has some stuff.
this.collection.on('reset', this.render);
// And go get the stuff we want. You can put your `error` callback in
// here if you want it, wanting it is a good idea.
this.collection.fetch();
}
现在为render:
render: function (todo) {
var templ = _.template(this.template);
this.listBlock.append(templ({
id: todo.get('id'),
content: todo.get('content'),
completed: todo.get('completed')
}));
// Mark completed
if(todo.get('completed')) {
this.listBlock.children('li[data-id="'+todo.get('id')+'"]')
.addClass('todo-completed');
}
}
通常这将分为两部分:
render渲染整个集合。
- 另一种方法,例如
renderOne,渲染单个模型。这也允许您绑定renderOne到集合的"add"事件。
所以这样的事情很典型:
render: function() {
// Clear it out so that we can start with a clean slate. This may or
// may not be what you want depending on the structure of your HTML.
// You might want `this.listBlock.empty()` instead.
this.$el.empty();
// Punt to `renderOne` for each item. You can use the second argument
// to get the right `this` or add `renderOne` to the `_.bindAll` list
// up in `initialize`.
this.collection.each(this.renderOne, this);
},
renderOne: function(todo) {
this.listBlock.append(
this.template({
todo: todo.toJSON()
})
)
// Mark completed
if(todo.get('completed')) {
this.listBlock.find('li[data-id="' + todo.id + '"]')
.addClass('todo-completed');
}
}
注意toJSON向模板提供数据的使用。骨干模型和集合有一种toJSON方法可以为您提供数据的简化版本,因此您不妨使用它。该模型id可作为属性使用,因此您不必使用get它来获取它。您可以(并且可能应该)将todo-completed逻辑推送到模板中,只需一点点
<% if(completed) { %>class="completed"<% } %>
在正确的地方应该可以解决问题。
addTodo: function (e) {
//...
var todo = new TodosModel({
id: todoID,
content: todoContent,
completed: todoCompleted
});
this.render(todo);
todo.save();
_this.collection.add(todo);
您可以绑定renderOne到集合的"add"事件来处理渲染新模型。然后使用save回调完成它:
var _this = this;
var todo = new TodosModel({ /* ... */ });
todo.save({}, {
wait: true,
success: function(model, response) {
// Let the events deal with rendering...
_this.collection.add(model);
}
});
同样,error回调save可能会很好。
completeTodo: function (e) {
//...
todo.save({
completed: todoCompleted
});
}
此处的save调用将触发一个'change:completed'事件,因此您可以绑定到该事件以调整 HTML。
removeTodo: function (e) {
//...
}
该destroy调用将触发"destroy"模型和集合上的事件:
为方便起见,在集合中的模型上触发的任何事件也将直接在集合上触发。这使您可以侦听集合中任何模型中特定属性的更改,[...]
因此,您可以侦听"destroy"集合上的事件并使用这些事件从显示中删除 TODO。销毁模型应该在没有您干预的情况下将其从集合中删除。
printColl: function () {
this.collection.each(function (todo) {
console.log('ID: '+todo.get('id')+' | CONTENT: '+todo.get('content')+' | COMPLETED: '+todo.get('completed'));
});
}
您可以console.log(this.collection.toJSON())改为,您必须单击一点以打开控制台中的内容,但您不会错过任何内容。
集合的所有事件绑定都将发生在您视图的initialize方法中。如果要删除视图,则需要覆盖removeto unbind 从集合中以防止内存泄漏:
remove: function() {
// Call this.collection.off(...) to undo all the bindings from
// `initialize`.
//...
// Then do what the default `remove` does.
this.$el.remove()
}
您还可以为每个 TODO 项目使用单独的视图,但这对于简单的事情可能是多余的。