私はbackbone.jsを使用して、バディリスト(別名Roster)を実装しています。名簿コレクションと個人の私のバックボーンビューは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()
、名簿ビューから関数を省略すると、名簿のすべてのエントリが削除されます。コンソールログ以外に何も含まれていないこのメソッドを追加すると、名簿とRosterEntry
ビューの両方でremoveメソッドが呼び出されます。理由はわかりませんが、順序が狂っています。
["Called remove event on model"]
["called remomve on collection"]
RosterEntryモデルからremove関数を削除すると、次のエラーが発生します。
TypeError: this.$el is undefined
this.$el.remove();
私は何が間違っているのですか?コレクションから削除されたときにDOMから要素を削除するにはどうすればよいですか?