1

I am using BackboneJS for my application. In my scenario, I have a collection (say booksCollection) with list of all the books (say model Book). I need to get a certain book based on the id and pass it to a view. I have the following code:

var book = booksCollection.get(1);
book.save(); // this obtained model is passed to some view, which makes few changes to the model and saves to the server

// booksCollection is a Backbone collection with model: Book

On inspecting book, I see that it has collection attribute with all the models in booksCollection. So, when trying to save (after setting few attributes) this model, I get this error "Too much recursion".

Is the model retured by invoking get method on a Backbone collection a readonly object?

As a quick fix, I am unsetting the collection attribute in book and then saving the model

book.unset('collection', { silent: true });

Is this a right approach?

Thanks, Anji

Anji
  • 725
  • 1
  • 9
  • 27
  • 1
    The `model.collection` property is just a reference to the collection, to which the model belongs. This is normal and expected. The code you describe looks fine. The error is caused by something else - a method that calls itself, or two methods, who keep calling each other, infinitely until the maximum call stack size is reached. I would look into your event triggers and listeners, can they lead into a situation where a triggers b, and b handler triggers a? – jevakallio Feb 01 '13 at 12:37
  • @fencliff I do not have any events in my `Model` or `Collection`. They are very simple objects. – Anji Feb 01 '13 at 12:39
  • How about views? Do you have a `change` handler on any models? In any case the error is not related to the code you posted so far. – jevakallio Feb 01 '13 at 12:41
  • I do not have any `Views`, just a simple collection and model – Anji Feb 01 '13 at 12:43
  • OK. If there's not much code, can you just post all of in a jsfiddle? Here's a fiddle with Backbone already loaded: http://jsfiddle.net/QqLT3/ – jevakallio Feb 01 '13 at 12:44
  • @fencliff Hey I figured out the problem, yes you were right about some events causing the problem. Thanks a lot! – Anji Feb 01 '13 at 17:03

0 Answers0