问题
I have a collection, and the collection.models
returns an array of models. However, when I call collection.get(someId)
(and this id is the id of the model that is in the collection.models
array), I get undefined
. Looking at collection._byId
, it looks like an empty object.
How do I properly populate _byId
, so that I can use get
? Or perhaps I'm doing something wrong when initializing my collection, which is why _byId
is empty.
回答1:
I'm a little late, but hopefully this is still useful to some other people.
Collection._byId is just a normal js hash object. There's really nothing fancy about it. If you want Collection.get to work, just add all the models into the _byId hash.
Inside the collection's scope:
var someId = '123'; // any id will do
this._byId[someId] = someModel; // someModel.id = '123'
console.log(!!this.get(someId)); // should return true
回答2:
Since I'm using this with Rails, the default json generated by Rails doesn't work well with Backbone. I don't know why I didn't see it while trying to learn Backbone. Anyway, you could either:
- Change the way Rails generates its JSON
- Change the way your Backbone app reads the JSON.
回答3:
Sounds like the OP had a slightly different problem, but I experienced a similar issue and thought I'd post what worked for me.
Like the original issue, collection.models
contained the right model, but in my case, the _byId
hash contained a cid version of the model that wasn't empty. Nevertheless, _byId
didn't contain a model with normal id (there's usually two version - an id
one and a cid
one), so I wasn't able to use collection.get(id)
to retrieve it. My problem became a bit clearer when I read up about cid
. From the docs:
Client ids are handy when the model has not yet been saved to the server, and does not yet have its eventual true id, but already needs to be visible in the UI.
I didn't think it was a problem with waiting for the server as my cid
model and the collection.model
had the correct ids. However passing in { wait : true }
as an option in collection.create
fixed this issue for me.
来源:https://stackoverflow.com/questions/10051471/how-to-populate-a-backbone-js-collections-byid-array-so-that-i-can-use-get-o