Sunday, March 2, 2008

Creating Useful Classes

Prototype makes it easy for you to create custom classes build in JavaScript that are extendable and reusable. Let's see some of this in action!

Let's make a class that holds our images for viewing in a slideshow or lightbox (for example).



var ImageLibrary = Class.create({
images: new Array(),
current_image: 0,
initialize: function($images_arr) {
this.images = $images_arr;
},
add_image: function($image) {
push(this.images, $image;
},
get_next: function(){
return this.images[this.current++];
},
get_previous: function(){
return this.images[this.current--];
},
get_current: function(){
return this.images[this.current];
}
});



This class is pretty basic and would hold Image information for us as well as a way to get the current and previous images (though no bounds checking, which should be added).

This class could be used alone, or with another class.



var img_lib = new ImageLibary(
new Array(
'/images/car.jpg',
'/images/jeep.jpg'
)
);

// Or with another class that
// takes the ImageLibarary class as an argument
var img_slideshow = new SlideShow(
new ImageLibrary(...)
);



The SlideShow would then have access to the ImageLibrary and all of its functions.

When to use Prototype's Features, and when not to

Prototype.js comes with a ton of features that makes it easy for you to access the DOM and make things easier for you to code in javascript. Even though useful, some are just overkill and add overhead. Take the following code example:



$('element')
.update('This is some element text')
.setStyle({font-weight: 'bold'});


versus



var ele = document.getElementByID('element');
ele.innerHTML = 'This is some element text';
ele.style.fontWeight = 'bold';



Prototype's Element object uses .update to set the element's text. However, it also parses the text for styles and scripts. Here we just don't need that and innerHTML is preferable. .setStyle also has considerable overhead and should be used sparingly. The preferable method is to use CSS or .addClassName

Practical Prototype

With this site, I hope to share some tricks and knowledge using prototype.js in a practical sense.