问题
I'm looking for an elegant way to prepend models to a collection when adding them. In the Backbone source code there is an unshift
method to do just that, but the add
method for adding models to a collection is too complex to simply extend. I'm building a slide show that depends on photos and tweets and should always show the newest on top, oldest last. Simplification of my problem:
Initialize app, API call returns:
apple, banana, lemon
So, apple is the newest slide. The collection is built:
apple, banana, lemon
After interval, API call checks if there are newer fruits, result:
orange
Collection appends model:
(apple, banana, lemon), orange
That's not what I want; orange is the newest fruit, and apple after that. But, in this case I could reverse my initial collection before appending and re-reverse when drawing slides. Now, things get more complex (I added parentheses to clarify):
API call checks for even more fruits:
pineapple, kiwi
Collection appends new models one by one:
((apple, banana, lemon), orange), pineapple, kiwi
So now from new to old, my collection looks like this:
((not so old, older, oldest), pretty new), brand new, new
Which makes absolutely no sense :)
Ofcourse, changing the API response could make my life easier, but that's currently not an option; also, it shouldn't really matter as the order of items in the response is new -> old which is fine by me.
I couldn't find an out of the box solution for this and I don't want to overcomplicate things by cloning part of the backbone source just to unshift
new models. Suggestions? Thanks!
回答1:
If the models have some kind of date or time associated with them or indeed any other kind of ordering (you can potentially add one manually if needed) you can sort the collection by implementing the comparator
function in your collection. See:
http://backbonejs.org/#Collection-comparator
来源:https://stackoverflow.com/questions/13178950/prepend-models-to-collection