javascriptbackbone.jscoffeescriptbackbone.js-collections

Backbone collection failing to remove all given models


After a collection is fetched, I'm adding "fake" models at the end, to make my flex grid work properly. Not happy with this solution but couldn't find a better one.

I want to support loading more models into the collection. So, on sync, I remove the old fake models (that would end up in the middle of the collection otherwise), then re-add them at the end.

onSync: ->
  modelsToRemove = @where({id: 0})
  console.log modelsToRemove, modelsToRemove.length
  // this prints:
  // [child, child, child, child, child]  5
  // which is expected
  @remove(modelsToRemove)

  modelsToRemove2 = @where({id: 0})
  console.log modelsToRemove2, modelsToRemove2.length
  // this should print
  // [] 0
  // right?
  // but it prints:
  // [child]  1
  // and the cid of the child is actually present in the first list...

  @add({}) for [1..@fakeCount]

How come remove removes all fake models except 1?

edit: got it to work properly by using the cids.

  modelsToRemove = _.map @where({id: 0}), (m, i) -> { cid: m.cid }
  @remove(modelsToRemove)
  @add({}) for [1..@fakeCount]

The issue seems to be related to the fact that several models are exactly the same except for the cid?


Solution

  • The fact that all these fake models have the same id breaks #get.

    The solution given to me on Github Issues was to give them different ids, and a fake property.