javascript – Backbone.Collection通過id獲取模型
我有一個從伺服器獲取模型的集合.
這樣做,現在我想用MyCollection.at(0)的id來獲取一個模型,我得到:
child _changes: Array[0] _changing: false _currentAttributes: Object _events: Object _hasComputed: true _pending: false _previousAttributes: Object attributes: Object _id: "50ef7a63b2a53d17fe000001" author_name: "author name" bookmark: "" info: "bookmark description" __proto__: Object changed: Object cid: "c26" collection: child view: child __proto__: Surrogate
如果我試圖通過它的id獲得模型:
MyCollection.get("50ef7a63b2a53d17fe000001") => undefined MyColleciton.get({_id:"50ef7a63b2a53d17fe000001"}) => undefined MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"}) => undefined
我不明白 – 文件清楚地表明.get()方法將返回模型,如果該集合中存在給定ID的模型.
Model.idAttribute
嗎?
var Model = Backbone.Model.extend({ idAttribute:"_id" });
預設情況下,Backbone希望將id屬性稱為id.當設定了idAttribute時,Backbone會標準化id的處理,以便始終可以使用model.id,即使id屬性被稱為別的東西.原始id屬性在Model的屬性雜湊中可用,並且通過getmetd可以使用.所以:
model.id === model.get('_id') // -> true
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/14299992/backbone-collection-get-model-by-id