Skip to content

model.id is not being added to a collection._byId hash table #2

@jmoretti

Description

@jmoretti

After digging into the problem of why I wasn't able to get a model from a collection using the Backbone.Collection.get() method, I discovered that the reason for this was because models are being added to the collection by pushing them directly into the Backbone.Collection.models array bypassing the Backbone.Collection.add() method which is where Backbone.Collection._byId is maintained. I can fix this by simply using the Backbone.Collection.push() method, but I noticed you had a comment directly above this snippet of code:

// do not use Collection methods!

The exclamation point means this must be serious...

Of course I can work around it by modifying it like so:

// do not use Collection methods!
var len = 0;
if (!opts.add) {
   collection.models = [];
}
var modelToBeAdded = [];
while (row = rows.nextRow()) {
   var m = collection.map_row(collection.model, row);
   if (m) {
      collection._byId[m.id] = m;
      collection.models.push(m);
      ++len;
   }
}

Out of curiosity, why don't we use the Backbone.Collection methods?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions