jQuery.addObject - Managing a Plugin's State With the jQuery API

By Ryan Florence, published 2010-10-05

Part of the issue Thoughtful jQuery Plugin Development.

Most plugins ought to provide a way for the developer to interact with it. Think of the holy accordion. Outside of just the click event on the togglers, you should provide a way to show a certain panel arbitrarily.

The jQuery docs provide a good hint on how to do this:

(function( $ ){

  var methods = {
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

// usage
$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method with options
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

The problem here is that every plugin you create will need something similar to lines 12-19. If you author your plugins with a constructor or John Resig’s simple inheritence instead, you can get all of the jQuery API with a simple:

jQuery.addObject('pluginNamespace', PluginObject);

For example

var Tooltip = function(selector, options){
  // this becomes `init`
}; Tooltip.prototype = {
  foo: 'bar',
  show : function( ) {},
  hide : function( ) {},
  update : function(content) {}
};

// add it to the jQuery API
jQuery.addObject('tooltip', ToolTip);

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method with options
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

// plus some more :)
$('div').tooltip('foo'); // => 'bar'
$('div').tooltip('foo', 'baz'); // => foo = baz

There’s even a bit more to it than that. Authoring plugins like this allows developers to take full advantage of your code–I tend to think it looks better too. You can download jQuery.addObject from github.

Hi, I'm Ryan!

Location:
South Jordan, UT
Github:
rpflorence
Twitter:
ryanflorence
Freenode:
rpflo

About Me

I'm a front-end web developer from Salt Lake City, Utah and have been creating websites since the early 90's. I like making awesome user experiences and leaving behind maintainable code. I'm active in the JavaScript community writing plugins, contributing to popular JavaScript libraries, speaking at conferences & meet-ups, and writing about it on the web. I work as the JavaScript guy at Instructure.