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(

// 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.

No comments: