Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Backbone Model instance's model/class name

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' 
like image 581
Blacksad Avatar asked Mar 13 '12 14:03

Blacksad


People also ask

What is a model backbone?

Model. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.


2 Answers

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; 
like image 187
Rob Von Nesselrode Avatar answered Sep 24 '22 15:09

Rob Von Nesselrode


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.

like image 32
Mitch Avatar answered Sep 25 '22 15:09

Mitch