December 14, 2006

Posted by John

Tagged prototype

Older: Two Really Handy Textmate Shortcuts

Newer: Finding Help Fast

Default Options for JavaScript Classes

Straight up, I love prototype. I can remember the days without it and they were annoying days. The application I’m currently building at work has led me to create a few fun javascript classes. No that is not an oxy moron, javascript can be fun. Nearly every js class I create has a few options so that I can reuse it more easily. In ruby, especially rails, default options are easy. For example, rails adds a method to hash named reverse_merge which allows easy method options like so:

def my_method(options = {})
  options.reverse_merge! :size => 25, :velocity => 10
  # any options that are passed into the method call overwrite the 
  # default options defined in the reverse merge method call
end

What you may or may not know is that you can do pretty much the same thing with your prototype javascript classes.

var Foo = Class.create();
Foo.prototype = {
	initialize: function(options) {
		this.options = $H({
			someOption: 'someValue',
			another: 'anotherValue'
		}).merge(options);
	}
}

$H is a method in prototype which adds several methods to a javascript hash. One of those methods is merge which works just like the ruby hash#merge (or hash#update). What is happening above? First, this.options is set equal to the default options and the $H methods are added to those default options. Then, the merge method replaces the default hash with any of the options that are passed in to the method call. For example:

new Foo({someOption: 'not the default'});
// this.options => {someOption: 'not the default', another: 'anotherValue'}

Botta bing bang boom. You now can have any number of options for your new js class but be sure to read Justin Palmer’s excellent article on avoiding bloat in widgets before going crazy.

0 Comments

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.