UsersView (リスト) によって処理される UserCollection があります。単一の要素であるモデルは、UserView として扱われます。
新しい UserCollection (他の URL) をフェッチすると、コレクション オブジェクト自体が更新されます (新しいユーザー モデルが含まれます) が、html リストは残ります。
リストビュー:
var ContactsView = Backbone.View.extend({
tagName: "ul",
className: "contacts unstyled",
events: {
},
initialize: function() {
this.collection = new UserCollection();
this.collection.bind('add', this.addContact, this);
this.collection.bind('remove', this.removeContact, this); // not getting called
this.collection.bind('reset', this.listContacts, this);
this.collection.fetch();
},
render: function() {
this.$el.html();
return this;
},
listContacts: function(contacts) {
contacts.each(function(contact) {
this.$el.append(new ContactView({ model: contact }).render().el);
}.bind(this));
},
addContact: function(contact) {
this.$el.append(new ContactView({ model: contact }).render().el);
},
// this is not getting executed
removeContact: function(contact) {
console.log(["removeContact fired"]);
contact.unset();
}
});
アイテムビュー
var ContactView = Backbone.View.extend({
tagName: "li",
className: "contact",
template: _.template(ContactTemplate),
events: {
"mouseenter li.contact": "expandOptions"
, "mouseleave li.contact": "collapseOptions"
, "click": "removeContact"
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('remove', this.remove, this);
this.model.bind('destroy', this.remove, this);
this.model.bind('unset', this.remove, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
expandOptions: function() {
},
collapseOptions: function() {
},
removeContact: function(e) {
this.model.destroy();
}
});
Backbone.Collection がアイテムを内部的に削除する (例: fetch) ときに発生するイベントと、それをリッスンする方法を教えてください。