Be very careful when you set the id of a Backbone model

May 10th, 2013 by admin Leave a reply »

I have been scratching my head all morning today trying to figure out why a collection I had on my backbone model was getting reset anytime I passed it to my views.  I tried everything, passing the collection to my view in functions, instantiating it in the initialize(), and a few other things that I can’t even remember right now, lol.  Anyways, I noticed down where we were adding items to the collection there was a line that looked like this:

that.model.set(“id”, evt.val, { silent: true });

Notice the lowercase “id” there.  What that is telling backbone is to actually set the id of the model instead of just setting the id to something we had planned to reference down the road, which would be fine in most situations, although I think backbone will do a PUT in those situations because it thinks the model has been saved before.  Anyways, when this was set in my app, it was clearing the collection whenever I passed it around, which was not cool.  All I had to do was change that to an uppercase “Id” and update any reference I had to it and all is well again, my collection stays intact.  I hope this helps someone.


Leave a Reply