【发布时间】:2012-07-26 09:15:49
【问题描述】:
我有一个由 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)时会触发哪个事件,我该如何收听呢?
【问题讨论】:
-
首先,绑定这个(信息:backbonejs.org/#FAQ-this),最好使用
_.bindAll-function。然后在所有每个类型函数之前,执行var self = this;,并且在任何你想调用它的地方(如你调用每个函数中的this)使用self。 -
那看看是不是不能正常工作
-
@jakee 为什么自我推荐优于 .bind(this)?
-
它们是一样的,没有注意到你有那个,对不起
标签: javascript events backbone.js