Friday, August 1, 2008

Easy Options

When creating reusable classes it it important that your object can be altered fairly easily. Today I'm going to discuss the Object.extend method, and how it is useful in creating reusable objects.




Let's take a simple class example of a custom input box and its label.

We want it to create something like



<label for="fname">First Name</label><input name="fname" type="text">




var CustomInput = Class.create({
initialize: function($options) {

// Default Options
this.options = {
name: 'textField',
type: 'text'
};

// Map $options over the top of this.options
// if $options is null use a blank object
Object.extend(this.options, $options || {} );
},

render: function(parent) {
this.label = new Element('label', {name: this.options.name});
this.input = new Element('input', {type: this.options.type, name: this.options.name});
parent.appendChild(this.label);
parent.appendChild(this.input);
}
});




This is the basic object. Later if we wanted to add validation to this object we would only have to pass in the validation parameters in the $options object. In this way, you are less likely to break things as your objects grow up over time.
Blogged with the Flock Browser