Search code examples
backbone.jsbackbone-viewsbackbone-routingbackbone-model

Get the name/type of a backbone model


I have a somewhat generic view that can except 6 different types of models.

I create the view and pass in the model like this:

 var view = new MyView({
                model: myModelType  //can be 1 of 6 different model types
 });

In the view, I need to display a subview, but only if the model is not of a certain type.

In the view, I only refer to the models like 'this.model'. Is there a way to figure out the type of model that was passed in?

I tried this but I get a warning:

if (this.model != ModelTypeA) { do stuff }

The warning was: Using a variable without declaring it is not allowed in script mode.

I also tried:

if (!this.model instanceof ModelTypeA)

But I get the same warning.

Is there a trick to getting the model type/name?

Thanks!


Solution

  • Um i tried it out and it looks right to me, are you using new?

    var A = Backbone.Model.extend({});
    var B = Backbone.Model.extend({});
    var AA = A.extend({});
    
    new A() instanceof Backbone.Model
    > true
    new AA() instanceof Backbone.Model
    > true
    new AA() instanceof A
    > true
    new A() instanceof B
    > false
    new B() instanceof A
    > false