Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
boolean Avatar asked Jun 17 '12 04:06

boolean


2 Answers

Not sure if this is new, but it looks like you can also just set the parse property of the options parameter to your constructor to true, thus telling the constructor to use your parse method:

modelInstance = new MyModel(obj, {parse: true});

http://backbonejs.org/#Model-constructor

like image 151
GxXc Avatar answered Oct 18 '22 09:10

GxXc


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.

like image 28
mu is too short Avatar answered Oct 18 '22 08:10

mu is too short