documentcloud/backbone — Issue #836: Hacking with `fetch` can cause `get(id)` to return `undefined`
Author: alanhogan
Created: 2012-01-03 23:14:15+00:00
State: open

I did something funky and got `.get(id)` to improperly return `undefined` (non-randomly).

Here’s what was going on (steps to reproduce):

1. Have a Collection (we’ll call it 'List')
2. Give it a method that does this:
* Takes a date range
* Calculates if any items in List are within that range, and saves them as `removeLater`
* Makes an ajax request for items within that range, by using `fetch` with some extra parameters (importantly, with `{add: true}`, and by passing a query for the range in question)
* On `success`, it removes the items in `removeLater` from List. (This prevents duplicates, and gets rid of any items that were deleted on the server, within that range.) Note however that by the time `success` fires, the data has already been parsed and added to the collection (this is why we pre-calculated `removeLater`.)
* Also note ranges can overlap, partially or completely or exactly, whatever
3. Use this method twice, ensuring some overlap. (for testing purposes, consider that there are three groups items can fall into: Only in the first range, only in the second, or in both ranges. I only see the funky behavior in the last case.)

What happens?

Well, if you do a `filter()` or `toJSON()`, etc., on our Collection, it will return items (which I do want to be in the Collection!), that have IDs that result in an `undefined` if to `get`!

This only happens for items that were already in the collection, then removed on `success` of that `fetch` Ajax request.

**So basically, it would seem that if you add an item to a Collection twice, then remove one of it, `get` breaks.** I haven’t tested a general case of this yet, just within my above situation.

(Note, at first I posted this [as a comment on #708](https://github.com/documentcloud/backbone/issues/708#issuecomment-3266254).)