I have a collection which sorts itself based on a model’s attribute, sometimes I want to add a model and just calculate the order within the add event handler. The problem is that when I call collection.sort() within the add event handler, for some reason it fires the add event again.
Since my add event does some DOM inserts, I end up getting duplicate items in my DOM.
So far the only solution I have found is to calculate the next order before adding the model or calling _.defer and sorting the collection then running any further code
See full fiddle: http://jsfiddle.net/DD23n/9/
sntran is right about where your problem is coming from: you’re modifying an array while you’re iterating over it.
You start off with your new model with
nOrder: nullat the beginning of the model list:then
addloops through the models triggering'add'events as it goes:But inside your
'add'callback, you modify the model:and then sort the collection:
These two actions move
this.models[0]tothis.models[3]in the event triggering loop; but theifor that loop will just keep ticking along and the newthis.models[3](which used to be at0) will get past theif (!cids[(model = this.models[i]).cid])test again and there’s your second'add'event.You can watch this version of your fiddle work to see how the collection’s array is changing behind your back:
I think the simplest solution is to add an
appendmethod to your collection that sets the appropriatenOrdervalue on the model and then adds it to the collection:Then your
'add'callback can leavenOrderalone and stop sorting the collection.Demo: http://jsfiddle.net/ambiguous/JqWVP/
You could also override the collection’s
addmethod but that is a lot more complicated if you want to do it right.