我有一個由UsersView(列表)處理的UserCollection。單個元素,模型以UserView的形式處理。如何刪除提取的項目視圖?
當我現在獲取一個新的UserCollection(其他url)比收集對象本身更新(包含新的用戶模型),但HTML列表仍然存在。
的ListView:
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內刪除項目被觸發(例如讀取)和我怎麼聽呢?
首先,綁定這個(info:http://backbonejs.org/#FAQ-this),最好用'_.bindAll'函數。然後,在所有每個類型函數之前,執行'var self = this;',並且你想調用它的任何地方(就像你在每個函數中調用的函數一樣)使用'self'。 – jakee 2012-07-26 09:34:27
然後看看它是否工作不正常 – jakee 2012-07-26 09:34:45
@jakee爲什麼自我建議over.bind(this)? – bodokaiser 2012-07-26 12:02:40