0

対応するモデルでidAttributeを設定しても、IDで単一のモデルを取得するのに問題があります。

コレクションは次のようになります。

[
    {
        "_account": "51dc04dbe4e643043d000001",
        "name": "test.png",
        "type": "image/png",
        "_id": "51ff833f0342ee0000000001",
        "added": "2013-08-05T10:49:35.737Z"
    }
]

// Inside the Model I defined idAttribute
FileModel = Backbone.Model.extend({

idAttribute : "_id",
urlRoot : "/api/file"

[...]

}
// The collection contain each of the Model items
// but if I try to get a single model item  by id:

Collection.get("51ff833f0342ee0000000001") -> the result is undefined

理由がわかりません.Backbone.Collection get model by idからの解決策は、問題を解決するための鍵ではありませんでした。

4

1 に答える 1

1

カスタム IDでモデルを取得するには、モデルでidAttributeを指定する必要があり、モデルを使用するにはコレクションのモデルプロパティを指定する必要があります。通常は、プロパティを宣言するコレクションでこれを設定するだけで十分です。

var MyCollection = Backbone.Collection.extend({
  model: FileModel,
  ...
})

ただし、JavaScript のレイアウト方法 (およびブラウザーによる JavaScript の評価方法) によっては、model: FileModelステートメントが読み取られた時点でまだ定義されていない可能性があります。これを回避するには、プロパティの割り当てをコレクションの初期化/コンストラクターに移動します。

例えば

var MyCollection = Backbone.Collection.extend({

        initialize: function () {
            this.model = FileModel;
        }
    ...
});
于 2013-08-05T14:20:07.563 に答える