2

I was curious if there was a way for me to set a collections model to a parent model. I may be way off here as I've just started with backbone.js but heres the structure I'm looking to do.

Collection  
  model:object

the object model is the parent model of two other sub-objects.

Object  
  ->Image  
  ->text  

The two sub models extend the Object model.

Is this do-able? I hope I am making myself clear here. Thanks to anyone who can offer any assistance.

rfunduk
  • 30,053
  • 5
  • 59
  • 54
Mike Depies
  • 777
  • 1
  • 6
  • 14
  • 1
    Have you tried?, in a first look I don't see any problem, except maybe a lot of conditional sentences are gonna appear to separate behaviors and rendering. – fguillen Mar 17 '12 at 16:36
  • Possibly related to [Backbone.Js Collection with Specific Types](http://stackoverflow.com/questions/6061445/backbone-js-collection-with-specific-types). – Julian D. Mar 18 '12 at 22:30

1 Answers1

4

Yes, this is doable.

I haven't used different subclasses in a collection myself, but here is a quite nice article about Backbone inheritance in general as well as "Subclasses in a Super Collection" in particular.

After setting up the inheritance itself the author uses the collections parse function to create corresponding models.

Backbone.Collection.extend({
    model: Location,
    parse: function (res) {
        _.each(res, function (location) {
            switch(location.phase) {
               case 'solid':
                  this.add(new Country(location));
               case 'liquid':
                  this.add(new Ocean(location));
               //...
            }
        }, 
        this);
     }
});

Regarding the inheritance part you might also wanna take a look at this question and JohnnyO's answer which might help your code design and avoid calls like

this.constructor.__super__.initialize.apply(this, arguments);
Community
  • 1
  • 1
SunnyRed
  • 3,525
  • 4
  • 36
  • 57
  • No need for the 'var self' part. Pass in 'this' as a final parameter to _.each to assign a context. i.e. _.each(res, func..., this); – backdesk Jan 06 '14 at 13:45