[英]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). 我试图使超类(MyShape)和子类(MyTriangle,MyRectangle)。 I already searched some backbone.js's polymorphism concept...but have no idea on this problem. 我已经搜索了一些bone.js的多态概念...但是对这个问题一无所知。
I hava a .json file like below 我有一个.json文件,如下所示
[
{
"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. 然后,我使用如下所示的ribs.js构造了继承结构。
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. 如上所示,超类(MyShape)具有color和src属性。 I hava a problem because of this. 因此,我有一个问题。 If I make MyTriangle instance I think I cannot use src or color attributes on that object. 如果我创建MyTriangle实例,我想我不能在该对象上使用src或color属性。
Q.If I want to make a code like below(this example is Java Based), how should I code it? 问:如果要编写如下代码(此示例基于Java),应该如何编码?
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). 我必须维护这种结构(MyShape,MyTriangle,MyRectangle)。
I really appreciate your help. 非常感谢您的帮助。
To use the default
from parent class, you need to extend the defaults of parent class. 要使用default
的父类,你需要扩展父类的默认值。
So, for example ( source ) 因此,例如( 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);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.