I am trying to sync a sorted Backbone.Collection
with another list, e.g. a JavaScript Array. I am using the following code (jsfiddle):
var coll = new Backbone.Collection();
coll.comparator = "label";
var list = []
coll.on("add", function (model, collection, options) {
list.splice(collection.indexOf(model), 0, model.get("label"));
});
coll.add([
{label: "1"},
{label: "3"},
{label: "5"},
{label: "4"},
{label: "2"}
]);
In this example, this results in the following list: 1, 2, 3, 5, 4
. The root cause is, that within the add event handler the Backbone.Collection is already filled with all models, while the JS array is not. Since the add events are triggered in insertion order, not sorted order, this leads to the wrong order in the array.
How would I change my sync approach/add handler to make things work?