0

I have a pretty complicated Backbone Model structure.

  • m.Question: is a base question. If this was C++ it would be an "abstract" model because only it's children are ever instantiated
  • m.NumericQuestion: extends m.Question
  • m.MultipleChoiceQuestion: extends m.Question
  • m......Question: you get it lots of question types
  • c.Questions: collection of m.Question children

When getting saved to the database they all have an attribute called "type" which decides what model it should be.

When raw questions are retrieved from server, they are placed in a Questions collection (c.Questions). Backbone should parse the response from the server and make the appropriate model based on type.

So I wrote a _prepareModel() function for c.Questions.

But when I do a c.Questions.fetch() I discovered that Backbone.Collection.prototype._prepareModel (the one Backbone relational has) is called first! Is there a way I can intercept the model creation beforehand?

Toli
  • 5,547
  • 8
  • 36
  • 56

1 Answers1

1

override the Model's parse function: http://backbonejs.org/#Model-parse

you can also do this for a Collection: http://backbonejs.org/#Collection-parse

like so:

var MyModel = Backbone.Model.extend){
    parse: function(resp) {
        // your parse function returns the attributes that you want your new model to have
    }
});

for a Collection, parse should return an array of attribute objects.

if you want to further manipulate the attributes after fetching, you can do something fancy in initialize, like make an attribute into another Backbone model, like so:

initialize: function() {
    this.set('attributeThatIsAnArray',new MyCollection(this.get('attributeThatIsAnArray')));
}

you can check out this other Stack Overflow question for another example: Converting JSON data to Backbone Model with child Collection

Community
  • 1
  • 1
georgedyer
  • 2,737
  • 1
  • 21
  • 25
  • I need something in between parase and initialize. Something that triggers right before creating the model. at initialize the model is already created. – Toli Jan 24 '13 at 23:15
  • then you should override the `constructor` method, which passes to ininitalize – georgedyer Jan 25 '13 at 00:07