Sebastien
Sebastien

Reputation: 6660

How to get model name from a collection with backbone.js

How can i get model name from a collection? When i define a collection, i specify the model attribute as :

Domains = Backbone.Collection.extend({
    model : Account
})

How can i get this attribute value?

I tried Domains.model...

Upvotes: 0

Views: 2887

Answers (1)

fguillen
fguillen

Reputation: 38792

First of all I don't think Backbone is gonna work if you use a String to initialize Collection.model, you have to specify a Model class reference like this:

var MyModel = Backbone.Model.extend({});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

Said that I don't this is possible to retrieve the name of a variable from the variable reference itself.

I suggest to come up with a workaround which is tagging every Model with a String class attribute to which you can ask wich is the name of the class:

var MyModel = Backbone.Model.extend({
    name: "MyModel"
});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

var myCollection = new MyCollection();

console.log( "reference", myCollection.model ); // reference to the class 
console.log( "reference.name", myCollection.model.prototype.name );​ // string name

Check the jsFiddle

Upvotes: 1

Related Questions