I’m new to backbone, so please bear with me. I would like to create a collection in which the models all have a handful of critical attributes which they share as well as a number of other attributes which they do not share. I thought the best way to do this would be to extend a superclass model (containing defaults for all of the shared attributes) such that when I instantiate a new subclass model, those attributes are initialized and additional attributes specific to the subclass are also added to the model. I don’t know how to accomplish this, but here is the direction I’ve been working in:
app.Fruit = Backbone.Model.extend(
{
defaults: {
name: "none",
classification: "none",
color: "none"
},
initialize: function()
{
console.log("Fruit Initialized");
}
});
app.Apple = app.Fruit.extend(
{
url: "/php/Apple.php",
initialize: function()
{
console.log("Apple initialized");
// somehow fetch additional information from server
// and add sublcass-specific attributes to model
// (for example, in the case of an apple, an attribute called cultivar)
}
});
var FruitCollection = Backbone.Collection.extend(
{
model: function(attributes, options)
{
switch(attributes.name)
{
case "Apple":
return new app.Apple(attributes, options);
break;
default:
return new app.Fruit(attributes, options);
break;
}
}
// ...
});
app.fruitCollectionCurrent = new FruitCollection([
{name: "Apple"},
{name: "Orange"}
]);
// logs: Fruit Initialized
Any suggestions on how to properly initialize a subclass with additional attributes would be appreciated.
Thanks.
EDIT: THE SOLUTION
I thought I would post the code that ended up working for me… Arrived at it thanks to @Mohsen:
app.Fruit = Backbone.Model.extend(
{
defaults: {
name: "none",
classification: "none",
color: "none"
},
initialize: function()
{
console.log("Fruit Initialized");
}
});
app.Apple = app.Fruit.extend(
{
url: "/php/Apple.php",
initialize: function()
{
console.log("Apple initialized");
return this.fetch();
}
});
I didn’t even really need the asynchronous call in the subclass because I wasn’t fetching any additional data for Fruit (Fruit’s attributes were just set in the constructor), only for Apple. What I was really looking for was the call to this.fetch() with the specified URL. Sorry if the question made things seem more complex…
Backbone is not easy to work with when it comes to hierarchy. I solve this problem by calling parent model/collection initializer inside of my child model/collection initializer.
Now your
Applemodel does have all properties of aFruit.Key line is
Fruit.prototype.initialize.call(this, arguments);. You call initialize method ofFruitforApple.You can also use
this.__super__to access parent model:this.__super__.prototype.initialize.call(this, arguments);