1

Check if passed parameter is Backbone.js view or command.

I'm passing a Backbone view into another as a parameter.

I need to test whether the passed function is a View and not a function of another type like a command for example.

What I came up with so far is something like this:

//content is the passed function
if (typeof content === 'function') {
        //do foo
}

This condition is true when you pass a function, which is true for both, commands and views.

So I need something like this:

if(view) {
    //do foo
} else if(command) {
    //do bar
}

Are there any unique attributes to Backbone views which I could check against?

Thank you!

Jannik Lehmann
  • 468
  • 5
  • 25
  • 1
    maybe you can solve it by using the "instanceof" comparator as : if (x instanceof Backbone.View) { ... } else if (...) . for more information on istanceof you can check: http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for – kawashita86 Dec 21 '16 at 10:43
  • 1
    @kawashita86 while you are right, you linked to a question on Java, and this questio is about JavaScript. – Emile Bergeron Dec 21 '16 at 15:06
  • 1
    @EmileBergeron whoops, my bad. From a fast read of the answer the logic behind was so similar that I didn't double check which language the code was. Thank you for poiting that out. :) – kawashita86 Dec 21 '16 at 17:40

1 Answers1

2

As mentionned by kawashita86, you can use instanceof to test whether a function is of a specific type somewhere up the prototype chain.

var MyViewType = Backbone.View.extend({}),
    myView = new MyViewType();


console.log("myView instanceof Backbone.View:", myView instanceof Backbone.View);

var MyOtherViewType = MyViewType.extend({}),
    myOtherView = new MyOtherViewType();

console.log("myOtherView instanceof Backbone.View:", myOtherView instanceof Backbone.View);
console.log("myOtherView instanceof MyViewType:", myOtherView instanceof MyViewType);
console.log("myOtherView instanceof MyOtherViewType:", myOtherView instanceof MyOtherViewType);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

More information:

Community
  • 1
  • 1
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129