How to correctly use the parse function in backbone.js

January 5th, 2013 by admin Leave a reply »

Ok, I have been looking for this example for a long time myself, so I thought I would post it to my blog for anybody strugging with this themselves. When you use fetch() to get a collection it does a great job of setting the properties of your model, the one thing it does not do is set nested collections, so I have an example below of using backbone’s parse() function and how to take your response that has arrays on it and turn those into new collections and set it back to your main model.

If you would rather use a library and have all your models structured nicely to have backbone handle the work for you, and you have a project that has a lot of models and collections, I would recommend looking into the Backbone-Relational library, it looks very nice. I kinda like to do my own thing and not get the overhead that comes with a third-party, plus this code is very small, vs. the amount of extra you would get with the third party, enjoy.

parse: function (response) {
            if (response != null) {
                response.YourCollection = new yourCollection(response.YourCollection);
                return response;
            }
        }

Advertisement

Leave a Reply