简体   繁体   English

Backbone.js:在Collection中使用时不会触发模型事件

[英]Backbone.js: Model events are not fired while used within a Collection

Here I have a Backbone.js Model - Contact and a Collection - Contacts with Contact as the Model. 在这里,我有一个Backbone.js模型 - 联系人和集合 - 联系人与联系人作为模型。 I've two views where in one I use collection to list all the contacts and in the second the model directly to show a single contact. 我有两个视图,其中一个我使用集合列出所有联系人,而在第二个模型中直接显示单个联系人。 But when I'm using the model directly I'm able to get the 'change' event fired while using with the collection the 'change' event, (even 'all' events of the model) is not fired. 但是当我直接使用模型时,我可以在使用集合时触发“更改”事件“更改”事件(甚至模型的“所有”事件)也不会被触发。 Am I missing some extra bind here to make it work with collection? 我在这里错过了一些额外的绑定以使其与集合一起工作吗?

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,
    ...
});

Update While using both collection & single model instances I have to run generateUrls() to update urlDisplayPicBig & urlDisplayPicSmall based on the 'id' of the model. 更新在使用集合和单个模型实例时,我必须运行generateUrls()以根据模型的“id”更新urlDisplayPicBig和urlDisplayPicSmall。

When you do fetch on a collection: 当您fetch集合时:

the collection will reset 该集合将重置

and that will 那就是

replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. 使用新的模型列表(或属性哈希值)替换集合,最后触发单个"reset"事件。 [...] Using reset with no arguments is useful as a way to empty the collection. [...]使用不带参数的reset可用作清空集合的方法。

So a fetch on a collection will remove all the models that are currently in the collection and replace them with brand new model instances. 因此,对集合的fetch将删除当前集合中的所有模型,并将其替换为全新的模型实例。 No "change" events will occur, there will only be a single "reset" event. 不会发生"change"事件,只会发生一次"reset"事件。

When you do a fetch on a model: 当您对模型进行fetch时:

A "change" event will be triggered if the server's state differs from the current attributes. 如果服务器的状态与当前属性不同,将触发"change"事件。

So calling fetch is pretty much the same loading the data from the server manually and calling set to change the model. 因此,调用fetch与从服务器手动加载数据并调用set来更改模型几乎相同。


Summary : Collection#fetch doesn't trigger any "change" events, just a "reset" event; 摘要Collection#fetch不会触发任何"change"事件,只会触发"reset"事件; Model#fetch will trigger a "change" event if something changes. 如果发生变化, Model#fetch将触发"change"事件。


If you just want to add a couple new attributes when creating new model instances then you can add new attributes to the incoming JSON using Model#parse . 如果您只想在创建新模型实例时添加一些新属性,则可以使用Model#parse向传入的JSON添加新属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM