Get a Backbone Model instance's model/class name

21,136

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.

Share:
21,136

Related videos on Youtube

Blacksad
Author by

Blacksad

Updated on August 20, 2022

Comments

  • Blacksad
    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
      JayC about 12 years
      You 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
      JayC about 12 years
      Ah, nevermind. You're talking programmatically.
    • websymphony
      websymphony about 12 years
      Why 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
      Blacksad about 12 years
      @websymphony I need it because I have a mix-in which at a certain stage requires the class name.
    • rxgx
      rxgx almost 12 years
      There 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 an extend method may be an easier way to implement inheritance via mixins.
  • fguillen
    fguillen about 12 years
    I agree, either you solve it manually as @JayC suggests or you are talking about a very old generic JS concern still not resolved.
  • dB.
    dB. over 11 years
    Note that this is not going to work if you have a minifier like Jammit, the constructor will change after packaging.