jQuery simpleWidget: a super-simple stateful widget factory

http://benalman.com/ http://gist.github.com/652131

by Ben Alman

HTML

<!-- see http://gist.github.com/652131 -->

<div id="a">aa</div>
<div id="b">bb</div>
<div id="c">cc</div>
<div id="d">dd</div>

CSS

div {
    border: 1px solid #000;
    padding: 1em;
    margin-bottom: 1em;
    position: relative;
}

.colorized {
    color: #fff;
    font-weight: 700;
}

.colorized span {
    position: absolute;
    top: 0.2em;
    right: 0.2em;
}

JavaScript

$(function(){
  
  $.simpleWidget( 'colorize', {
    options: {
      color: 'green'
    },
    _create: function() {
      // Perform widget-create code here.
      this.element.addClass( 'colorized' );
      this._label = $('<span/>').appendTo( this.element );
      this.value( this.options.color );
    },
    destroy: function() {
      // Perform widget-destroy code here.
      this._label.remove();
      this.element
        .removeClass( 'colorized' )
        .removeAttr( 'style' );
    },
    value: function( color ) {
      // A custom method!
      if ( color ) {
        this.color = color;
        this._label.text( 'Color: ' + color );
        this.element.css({ background: color });
      } else {
        return this.color;
      }
    }
  });
  
  $('#a, #b, #c').colorize();
  
  $('#b').colorize( 'value', 'blue' );
  
  $('#c').colorize( 'destroy' );
  
  $('#d').colorize({ color: 'red' });
  
  $('div:colorize').each(function(){
    $('body').append( this.id + ': ' + $(this).colorize( 'value' ) + '<br/>' );
  })
});


/*!
 * jQuery simpleWidget - v0.1pre - 10/28/2010
 * http://benalman.com/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

(function($,undefined){
  '$:nomunge'; // Used by YUI compressor.
  
  $.simpleWidget = function( widget_name, widget ) {
    // Create selector.
    $.expr[':'][ widget_name ] = function( elem ) {
      return !!$.data( elem, widget_name );
    };
    
    // Create plugin method.
    $.fn[ widget_name ] = function( options ) {
      var args,
        args_to_slice = 0,
        method_name = '_create',
        result;
      
      // Was a method name passed as the first argument?
      if ( typeof options === 'string' && $.isFunction( widget[ options ] ) ) {
        method_name = options;
        args_to_slice = 1;
      }
      
      // Parse the passed arguments.
      args = Array.prototype.slice.call( arguments,...