Reputation: 11725
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
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
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