Get a Backbone Model instance's model/class name
Solution 1
It's problematic in general, I think. I was going to suggest some of the options mentioned here ( How do I get the name of an object's type in JavaScript? ) but I was having issues with the first option. You could always extend all your models to have a function that returned a "name" for the model, but I can understand why you might find that less than satisfactory.
Solution 2
I tried Mitch's suggestion but in Chrome, model.constructor.name is always ""
for me.
I chose instead to use a convention. I now create a class property using the second param of extend that works as follows:
directory.models.SomeModel = Backbone.Model.extend({
// usual model instance stuff
}, {
modelType: "SomeModel" // class property
});
I found that I can always get what I want like this:
var mt = model.constructor.modelType;
Solution 3
As of writing you can get a model's class name by doing the following:
model.constructor.name
This works for me in the Chrome browser.
Related videos on Youtube
Blacksad
Updated on August 20, 2022Comments
-
Blacksad over 1 year
Given an instance of Backbone model, how can I know the "class" (so to speak) of this instance ?
For instance:
class Car extends Backbone.Model mycar = new Car()
And what I need is:
mycar.modelName # => 'Car'
-
JayC about 12 yearsYou need to be more specific. A model could have multiple views. The view has the .el reference which AFAIK should be enough, if you are considering views. But that may not be what you're asking about.
-
JayC about 12 yearsAh, nevermind. You're talking programmatically.
-
websymphony about 12 yearsWhy do you need the classname? To create a new model of same type or to access a class level function or something else? Its interesting question.
-
Blacksad about 12 years@websymphony I need it because I have a mix-in which at a certain stage requires the class name.
-
rxgx almost 12 yearsThere won't be a notion of class in JavaScript for another 5 years (ECMAScript 6+?). The object creation syntax of CoffeeScript causes much confusion to those just getting familiar with the language. Using
Object.create
and anextend
method may be an easier way to implement inheritance via mixins.
-
-
fguillen about 12 yearsI agree, either you solve it manually as @JayC suggests or you are talking about a very old generic JS concern still not resolved.
-
dB. over 11 yearsNote that this is not going to work if you have a minifier like Jammit, the constructor will change after packaging.