Search code examples
javascriptbackbone.js

backbone.js - using parse without calling fetch


On page load I'm bootstrapping my data to my collections via this technique. That works great, but I'm running into an issue where I have sub-models which also need to be cast.

For example, I return a JSON collection called Book, and each book array contains 10-20 models themselves called Pages. If I try and access Pages directly, I get the [object][object] error as Backbone can't figure out what type of object it is.

Previously when I was using fetch, I would get around this by using collections which contained a parse action. In parse I would do something like:

Collection_Books = Backbone.Collection.extend({
    model: Model_Book,
    parse: function (response) {
        response.Pages = new Collection_Pages(response.Pages);
        return response;
    }
});

Now that I'm accessing the data directly and not using fetch, the documentation implies that I no longer have access to the parse method.

If I am not using fetch or calling a server on page load, how can I cast sub-models using the Books > Pages example?


Solution

  • Update: This answer is now out of date, see uglymunky's answer for more up to date information.


    You're right, parse is only specified to be called during fetch so it won't be called when you're building a collection from raw data.

    But, since you control the raw data that you're using to bootstrap your collection, you can call your collection's parse yourself:

    var c = new YourCollection(
        YourCollection.prototype.parse([
            // attribute data goes here...
        ])
    );
    

    Demo: http://jsfiddle.net/ambiguous/kdaZ3/

    Your parse methods (both collection and model) shouldn't care about their calling context so calling them directly from the prototype should be fine.