这里我有一个 Backbone.js 模型 - 联系人和一个集合 - 以联系人为模型的联系人。我有两个 View ,其中一个 View 使用集合列出所有联系人,第二个 View 使用模型直接显示单个联系人。但是,当我直接使用模型时,我能够在与集合一起使用“更改”事件(甚至模型的“所有”事件)时触发“更改”事件。我是否在这里缺少一些额外的绑定(bind)以使其与集合一起使用?
var Contact = Backbone.Model.extend({
defaults: {
id: 0,
urlDisplayPicBig: '',
urlDisplayPicSmall: ''
},
initialize: function () {
this.bind('change', this.doSomething);
},
generateUrls: function () { //earlier doSomething()
...
}
...
});
var Contacts = Backbone.Collection.extend({
model: Contact,
...
});
更新 在使用集合和单个模型实例时,我必须运行generateUrls()来根据模型的“id”更新urlDisplayPicBig和urlDisplayPicSmall。
最佳答案
当你这样做时fetch
关于集合:
the collection will reset
replace a collection with a new list of models (or attribute hashes), triggering a single
"reset"
event at the end. [...] Using reset with no arguments is useful as a way to empty the collection.
因此,对集合进行 fetch
将删除集合中当前的所有模型,并用全新的模型实例替换它们。不会发生“change”
事件,只会发生一个“reset”
事件。
当您执行 fetch
时在模型上:
A
"change"
event will be triggered if the server's state differs from the current attributes.
因此,调用 fetch
与手动从服务器加载数据和调用 set
几乎相同。更改模型。
摘要:Collection#fetch
不会触发任何“change”
事件,只是触发“reset”
> 事件;如果发生变化,Model#fetch
将触发 “change”
事件。
如果您只想在创建新模型实例时添加几个新属性,则可以使用 Model#parse
将新属性添加到传入的 JSON 中。 .
关于javascript - Backbone.js:在集合中使用模型事件时不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10468325/