So you set a breakpoint here:
_.each(that.collection, function (gist) {
and see that that.collection
is empty but your console.log
:
console.log(['index to render', that.collection]);
suggests that that.collection
has one model. I suspect that you're seeing two confusing behaviors at the same time:
console.log
throws a live reference to its arguments into the console, it doesn't take a snapshot of their current state. So, if something changes between the console.log
call and when you look at the console, you'll see the changed version rather than the one you think you logged.
Collection#fetch
is an AJAX call and A stands for Asynchronous.
So the sequence of events probably looks like this:
- You
collection.fetch()
which fires off an AJAX call.
- You say
v = new View({ collection: collection })
and v.render()
.
console.log
is hit and a reference to the collection gets stashed in the log.
- You get to your breakpoint and find an empty collection.
- The server responds to the AJAX call and the collection gets populated with one model.
- You look at the console and find a collection with one model in it.
- Confusion.
The solution is to bind your rendering to events on the collection and make sure your render
can handle an empty collection in a sensible fashion.
And be careful with using console.log
to help you debug asynchronous things, you'll have to take your own snapshots (console.log(collection.toJSON())
for example) if you want consistent and sensible results.
PS: console.log
is a variadic function, you can give it as many arguments as you want:
console.log('index to render', that.collection);
Also, a collection contains a list of models but it isn't actually the list itself. So doing things like _.each(collection, ...)
won't spin you through the models, it will spine you through a bunch of internal properties that you probably don't care about. You want to iterate over the models:
_.each(collection.models, ....)
or better, use the built-in Underscore methods:
collection.each(...)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…