Garrett
Garrett

Reputation: 11725

Get a Backbone View's Parent class from an instance

I am implementing a system where I manage view switching in order to clear any events carried by that view before rendering another. However, I need to look up the view in an array using an instance of the view. How can I get the view class of a view instance?

eg:

var myView = new MyView;
return myView.parent(); // this should return MyView

Thanks!

Upvotes: 3

Views: 834

Answers (2)

mu is too short
mu is too short

Reputation: 434615

Sounds like you're looking for the constructor property:

Returns a reference to the Object function that created the instance's prototype.

So if you do this:

var v = new View;

then v.constructor will be View. And if you do this:

var views = [
    Backbone.View.extend({}),
    Backbone.View.extend({}),
    Backbone.View.extend({})
];

var v = new views[1];
for(var i = 0; i < views.length; ++i)
    if(v.constructor === views[i])
        console.log(i)

You'll get 1 in the console. Demo: http://jsfiddle.net/ambiguous/EgURK/

Upvotes: 3

buley
buley

Reputation: 29208

The way I solve this is to pass in this as part of the constructor and set an "instance variable" inside of the view.

You'd then wire up a getter function with the name "parent" to return it a la your example code:

var myView = new MyView( this );
return myView.parent();

Upvotes: -1

Related Questions