baalexander
baalexander

Reputation: 2589

Get the model type for a passed in backbone.js model instance

How do I retrieve the model name for a backbone.js model instance?

For example:

var Topic = Backbone.Model.extend({

})
var topic = new Topic({ type: 'question' })

var doSomethingWithTopic = function(topic) {
  // check if passed in topic is of type Topic
  // something like topic.constructor.name === 'Topic'
}

doSomethingWithTopic(topic)

I realize I may be blurring the line between a backbone.js model and a class, so I am open to other ways of going about this if needed.

Upvotes: 8

Views: 8072

Answers (1)

Lee
Lee

Reputation: 13542

Use the instanceof operator.

var doSomethingWithTopic = function(topic) {
  if( topic instanceof Topic ) {
    // do something with topic
  }
}

Upvotes: 20

Related Questions