Feb
10th

JavaScript Options Object

I don’t know how many times in the past I have found myself using a class and I want to change only one of the optional parameters but it just so happens to be the last argument.  In order to avoid changing the default value I have to look at the objects source code.  There are two ways to avoid this issue.

The first is to create setter functions for each option.  I have several problems with this solution:

  1. It requires time to create separate functions.
  2. It requires more code and that means larger file size.
  3. Creates more functions to document.
  4. I like formatting my code so that I only have have one function on each line.
  5. If I want to change three default options that means I will now have possibly 3 more lines of code.

The second way is to have parameter that allows options to be passed as a JSON object. It uses default options that can be over written just by sending in a JSON object specifying only the settings you want to overwrite.

Example:

   1:  Menu = {
   2:      initialize: function(button, menuElem, options)
   3:      {
   4:          this.button = (button);
   5:          this.menuElem = (menuElem);
   6:          this.setOptions(options);
   7:      },
   8:      setOptions(options)
   9:      {
  10:          this.options =    { align:'center', hide:true}
  11:          // extra {} prevents extending with null
  12:          Object.extend(this.options, options || {});
  13:      }
  14:  }
  15:  Woo = new Menu('myButton', 'myMenu', { hide: false });

This way of doing things is not my idea.  Not even close.  jQuery uses it as do many others.  The first place I saw it was two years ago in Rico JavaScript library.

So why am I revisiting this method of option handling? It is because my next post will cover how to port this brilliant methodology to PHP5.

Tags: ,

Leave a Reply