jashkenas / jashkenas/backbone
'add' events raised in unexpected order for Collection.set
- Dominant language
- JavaScript
- Stars
- 28.1k
- Forks
- 5.3k
- PR merge metrics
- No merged PRs in 30d
Description
I stumbled upon a feature of `Collection.set` which surprised me slightly. On reflection I don't think it's a bug but I wanted to let you know about it so you can decide if you want to do anything about it.
1. I have a Collection that defines a comparator.
2. I add an 'add' event handler to the collection that will create a new view for the new model, render it and add it to the DOM.
3. I populate the collection with multiple models either by calling `Collection.set([model1, model2], {sort: true})` or by calling `Collection.fetch({sort: true})`.
4. The collection is populated and sorted correctly BUT
5. The 'add' events are raised in the original order that the models are passed to the collection, not the sorted order.
In my own code I have worked around this by calling `Collection.reset` instead of `Collection.set` (or when fetching, doing `Collection.fetch({reset: true, sort: true})` instead).
I have created a JS Bin that demonstrates this: http://jsbin.com/voquvicoli/1/edit?html,js,output
Hope you don't mind but I also created a blog post describing the behaviour so that if anyone else encountered it they would know to use 'reset' instead of 'set': http://can-we-code-it.blogspot.co.uk/2015/06/add-and-reset-events-from-backbone.html
Contributor guide
Research direction
Start with the Collection.set and Collection.fetch entry points, then reproduce the ordering described in the linked JS Bin. Compare the observed add-event order with the sorted collection state and the reset workaround; done requires an agreed intended event-ordering behavior and corresponding project coverage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100