我有以下 Backbone.js 模型和集合:
// Model
lr.Event = Backbone.Model.extend({});
// Collection
lr.Events = Backbone.Collection.extend({
model: lr.Event,
initialize: function(models, options) {
this.date = options.date;
},
url: function() {
return '/events' + '?date=' + this.date.toString('yyyy-MM-dd');
}
});
与 View 及其 subview 一起使用:
// View
lr.MapView = Backbone.View.extend({
el: $('#wrapper'),
initialize: function() {
this.date = this.options.date;
_.bindAll(this, "render", "addAllEvents", "addOneEvent", "showNextDay", "collectData");
this.collectData();
},
events: {
"click #next": "showNextDay",
},
collectData: function() {
var that = this;
if (this.collection) this.collection.reset();
this.collection = new lr.Events([], { date : this.date });
this.collection.fetch({
success: function(resp) {
that.render();
that.addAllEvents();
}
});
},
showNextDay: function() {
this.date = this.date.add(1).days();
this.collectData();
},
addAllEvents: function() {
this.collection.each(this.addOneEvent);
},
addOneEvent: function(e) {
var ev = new lr.EventView({
model: e,
parentView: this
});
},
...
});
// Sub-view
lr.EventView = Backbone.View.extend({
initialize: function() {
var that = this;
this.model.bind('change', function() {
console.log('foo');
that.remove();
});
}
...
});
我正在尝试将 subview 绑定(bind)到其关联模型的更改。所以我希望当我调用 this.collection.reset()
时,会调用 console.log('foo')
。但事实并非如此。我在重置集合之前和之后都对集合进行了console.log编辑,它肯定会从“有到无”,所以我认为我以某种方式弄乱了 subview 的绑定(bind)到模型。
有人看到这个错误吗?
最佳答案
在没有模型的情况下调用reset()
会清空集合,但不会“更改”现有模型。当模型的某些属性 changes 时,'change' 事件发生。 。调用 reset()
确实会触发集合本身的 'reset' 事件(当您获取集合时也会触发);当此事件被触发时,您还应该重置您的 UI,创建并渲染所有 subview 项(在您的情况下,当您收到重置事件时,您似乎会调用 render 和 addAllEvents)
。
this.collection.on('reset', this.removeExistingEventViewsThenAddAllEvents, this);
现在,当事件模型的某些属性发生更改时,您将调用更改处理程序:
this.model.bind('change', function() {
console.log('foo');
that.remove();
});
但是,我真的怀疑您想在模型更改时删除事件 View 。更有可能的是,您想要重新渲染它,或者使用 JQuery 更新它的某些部分。
关于javascript - 为什么主干 View 检测不到模型更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9273089/