I have
data = {
"name1": "id1"
, "name2": "id2"
, "name3": "id3"
, "name4": "id4"
, "name5": "id5"
}
var MyCollection = Backbone.Collection.extend({
model: Backbone.Model
})
var myCollection = new MyCollection();
myCollection.fetch({
success: function(collection, response) {
var i = 0;
for (var name in data) {
if ( !data.hasOwnProperty( name ) ) continue;
(function(theName) {
var obj = collection.at(i).get('object');
obj.id = data[theName];
obj.displayName = theName;
collection.at(i).set({"object": obj});
})(name);
i++
}
}
})
The response contains
[
null
, {
"_id" : "some id"
, "object": {
"displayName": "name1"
, "id": "id1"
}
}
, null
, {
"_id" : "some id"
, "object": {
"displayName": "name1"
, "id": "id1"
}
}
, null
]
Some of the null value is because they does not exist in database. The collection on fetch will create a default model for those null, which the same structure, but no _id, and properties of object are empty strings.
The problem I have is after the loop, all the models has the same attributes as the last one in data, i.e., name5 and id5. I checked obj in each iteration, and it was indeed the same object. Thus, for each iteration, all models in the collection is set the same attributes.
Variable name in each iteration changes according to data, as well as i is increased. I also put the iteration inside a closure to make sure the scope is right.
Why Backbone behaves that way?
Update
It turned out that because of those null values in the response that made Backbone model behave so weird. I overridden parse function in the collection to set default values for the null object instead of relying on defaults value of the model, and it works.
I haven’t looked at the code in detail, but I have a hunch. Would this work?