The Rect Class
© 2012, Martin Rinehart
We got tired of creating styles objects with properties like this:
{ height: '50px', left: '100px', position: 'absolute', top: '30px', width: '200px' }
The flexibility of the styles object is certainly a Good Thing, but all that typing is not. Since we were regularly positioning and sizing new div elements in our DOM, we created a class that lets us type in the position and size arguments the old-fashioned, but fast, way.
var r0 = new Rect( 100, 30, 200, 50 );
Unlike the sample styles, our arguments are not in alphabetic order. Rather, they are position first, size second. In both, the horizontal (x) component precedes the vertical (y)—that's left, top, then width, height.
In addition to the position/size values, you can also pass a styles object argument. If you want a red rectangle, for example, you could create it this way:
var red_rect = new Rect( left, top, width, height, {background: 'red'} ); red_rect.draw( parent );
The large green div (samples_div
in our JavaScript) is a div declared in the HTML and styled with CSS, the old-fashioned way. The samples inside it are all Rect
objects. If we had created, as an example, that red Rect
in a simple, direct way, it would have been done like this:
var red_rect = new MRlib323.Rect( 10, 30, 250, 100, {background: 'red', border: '5px double white'} ); red_rect.draw( samples_div );
We chose a form that's more compact as we felt like adding a lot of Rect
objects. Think about it. Use your browsers "View Source" feature to take a look at our code.
What is that circle doing there among all the Rect
s? Well, there's no law that says a Rect
can't have round corners, is there? Again, "View Source" if you don't get it. Use a browser other than your old MSIE if you don't see it.
We never extend host objects, such as a div. We always wrap them in our own object. This means that the DOM div is embedded in the Rect
object as Rect.div
. If you want to modify a Rect's embedded div after the Rect
is created (or even after it is drawn) you can add to/replace properties of Rect.div.style
.
At present we are creating but not discarding Rect
instances. If we were to start throwing old Rect
s away, we would write a "destructor" method, like Rect.delete()
. This is normally not needed in JavaScript, but one browser cannot seem to debug its code so you need to detach its elements from the DOM before you delete them. See our library method detach_element()
if you need to delete Rect
s.
Feedback: MartinRinehart at gmail dot com
# # #