【发布时间】:2012-04-16 17:10:17
【问题描述】:
我正在使用backbone.js 来实现一个好友列表,也就是名册。我对名册集合和个人rosterEntry 的主干观点如下:
Slx.Roster.Views.RosterEntry = Backbone.View.extend({
tagName: "li",
className : "rosterEntry clearfix",
templateSelector: '#rosterEntryTemplate',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.model.bind('remove', this.remove);
this.template = _.template($("#rosterEntryTemplate").html());
},
remove: function () {
debug.log("Called remove event on model");
$(this.el).remove();
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
this.id = this.model.Id;
$(this.el).attr('id', "friendid-" + this.model.get("id")).html(renderedContent);
return this;
}
});
Slx.Roster.Views.Roster = Backbone.View.extend({
el: "div#roster-container",
initialize: function () {
_.bindAll(this, 'render', 'add', 'remove');
this.template = _.template($("#rosterTemplate").html());
this.collection.bind('reset', this.render);
this.collection.bind('add', this.add);
this.collection.bind('remove', this.remove);
},
add: function (rosterEntry) {
var view = new Slx.Roster.Views.RosterEntry(
{
model: rosterEntry
});
$(this.el).append(view.render().el);
},
remove: function (model) { // if I ommit this then the whole collection is removed!!
debug.log("called remomve on collection");
},
render: function () {
var $rosterEntries, collection = this.collection;
$(this.el).html(this.template({}));
$rosterEntries = this.$('#friend-list');
_.each(collection.models, function (model) {
var rosterEntryView = new Slx.Roster.Views.RosterEntry({
model: model,
collection: collection
});
$(this.el).find("ul#friend-list").append(rosterEntryView.render().el);
}, this);
return this;
}
})
我现在正在使用 Firebug 控制台进行测试,可以通过执行以下命令很好地填充花名册:
collection = new Slx.Roster.Collection
view = new Slx.Roster.Views.Roster({collection:collection})
collection.fetch()
通过在 Firebug 控制台中执行以下命令,添加到集合也可以正常工作:
collection.add(new Slx.Roster.Model({username:"mickeymouse"})
并且新的rosterEntry 被添加到名册中。
我的问题是 collection.remove(5) 从内存集合中删除,但没有更新 DOM。
奇怪的是,如果我从名册视图中省略 remove() 函数,名册中的所有条目都会被删除。如果我添加这个方法,除了控制台日志之外什么都没有,它会调用 Roster 和 RosterEntry 视图上的 remove 方法 - 虽然我不知道为什么,但它们有问题!
["Called remove event on model"]
["called remomve on collection"]
如果我从 RosterEntry 模型中删除删除功能,我会收到此错误:
TypeError: this.$el is undefined
this.$el.remove();
我做错了什么?从集合中移除元素时,如何从 DOM 中移除元素?
【问题讨论】: