Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if something is a Raphael object?

Given a JavaScript object, how can I check if it is a Raphael object (not the paper, but a circle, path, etc.)?

Raphael.el represents the generic element prototype; I think I want to test

x.__proto__ === Raphael.el

in a cross browser way, but I am not completely sure.

like image 831
Sophie Alpert Avatar asked Jun 25 '11 03:06

Sophie Alpert


1 Answers

To elaborate a little and add some more relevant info (it took me a little while to figure out the accepted answer, and I'm clearly not alone looking at the other answers, also, the accepted answer only works for one type of Raphael object: it solves the original question, this is a more complete resource).


Detecting Raphael elements

Using x.constructor.prototype == Raphael.el, you're taking x, the variable that might be a Raphael element (circle, path etc - not a Raphael set or paper object) and comparing the prototype of the function that constructed it with the prototype for Raphael elements in Raphael itself (Raphael is a function object, el is a defined property of it).

This works, but it also won't find raphael objects based on different prototypes to Raphael.el, like sets and paper objects:


Detecting Raphael sets

If you wanted to test if something was a Raphael set, the set prototype is in Raphael.st so you could test if a variable is a Raphael set using:

someSet.constructor.prototype == Raphael.st


Detecting Raphael paper objects

As for the equivalent for sniffing Raphael paper objects, since they are created using Raphael() function, you can use:

paper.constructor.prototype == Raphael.prototype


The above three are basically the same as...

someSet.constructor.prototype == paper.circle().constructor.prototype

...or...

someSet.constructor.prototype == paper.set().constructor.prototype

...or...

someSet.constructor.prototype == Raphael().constructor.prototype

...but without actually running those functions, so avoiding wasted processing (and avoiding Raphael() complaining that it hasn't been passed an ID).


Detecting sub-types of object (e.g. rectangle, circle...)

None of the above works for subtypes of Raphael elements - e.g. if you compare a circle with R.rect().constructor.prototype, it returns true.

This is because both circles and rectangles are made using the element prototype defined in Raphael.el. For these, however, Raphael makes it easy:

someRectangle.type == "rect"

someCircle.type == "circle"

...etc..

like image 154
user56reinstatemonica8 Avatar answered Sep 23 '22 13:09

user56reinstatemonica8