Backbone.Collection get model by id

后端 未结 2 1419
说谎
说谎 2021-01-11 09:22

I have a collection that fetches models from server.

This works, now I want to grab a model by its id with MyCollection.at(0) and I get:



        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 09:47

    Have you set Model.idAttribute on the Model?

    var Model = Backbone.Model.extend({
        idAttribute:"_id"
    });
    

    By default Backbone expects the id property be called id. When the idAttribute has been set, Backbone standardizes handling of ids so that model.id is always available, even if the id property is called something else. The original id property is available in the Model's attributes hash, and as such via the get methd. So:

    model.id === model.get('_id') // -> true
    

提交回复
热议问题