Search code examples
javascriptinheritancebackbone.jspolymorphism

How can I use backbone.js's polymorphism, especially super's attributes?


I am trying to make super-class(MyShape) and sub-class(MyTriangle, MyRectangle). I already searched some backbone.js's polymorphism concept...but have no idea on this problem.

I hava a .json file like below

[
{
    "type": "rect",
    "x": 10,
    "y": 10,
    "w": 100,
    "h": 100,
    "color": "red"
},
{
    "type": "arc",
    "x": 210,
    "y": 20,
    "w": 200,
    "h": 150,
    "color": "blue"
}
]

And I made inheritance structure using backbone.js like below.

    var MyShape = Backbone.Model.extend({
        defaults : {
            color : '',
            src : '',
        }
    });

    var MyRectangle = MyShape.extend({
        defaults : {
            x : 0,
            y : 0
        }
    });

    var MyTriangle = MyShape.extend({
        defaults : {
            x : -10,
            y : -10
        }
    });

    var Collection = Backbone.Collection.extend({
        model : MyShape,
    });

As you can see above, the super class(MyShape) has color and src attributes. I hava a problem because of this. If I make MyTriangle instance I think I cannot use src or color attributes on that object.

Q.If I want to make a code like below(this example is Java Based), how should I code it?

    MyShape myShape = null;
    if (type.equals("rect")) {
        myShape = new MyRectangle(x, y, w, h);
    } else if (type.equals("arc")) {
        myShape = new MyArc(x, y, w, h);
    } else if (type.equals("triangle")) {
        myShape = new MyTriangle(x, y, w, h);
    } else {
        return null;
    }


    // option - src or color
    if (jsonObject.has("src")) {
        myShape.setImg(jsonObject.get("src").toString());
    } else if (jsonObject.has("color")) {
        myShape.setColor(jsonObject.get("color").toString);
    } else {
        return null;
    }

I have to maintain this structure(MyShape, MyTriangle, MyRectangle).

I really appreciate your help.


Solution

  • To use the default from parent class, you need to extend the defaults of parent class.

    So, for example (source)

    var MyRectangle = defaults : _.extend({}, MyShape.prototype.defaults, {
            x : 0,
            y : 0
         })
    });
    

    To use polymorphic models in backbone collection (source, similar question)

    A collection can also contain polymorphic models by overriding this property with a constructor that returns a model.

    var Library = Backbone.Collection.extend({
    
       model: function(attrs, options) {
         if (condition) {
          return new PublicDocument(attrs, options);
        } else {
        return new PrivateDocument(attrs, options);
        }
      }
    });
    

    An example putting it all together