Josh
Josh

Reputation: 16532

Creating a jquery plugin with jquery ui-like parameter acceptance

I am trying to create a plugin very that has similar usage to the jquery ui plugin for dialogs. The usage I am after looks like this

First, to set options for my plugin (with a default action) you could pass in params like this.

$('#myId').dialog({
    value1 : 'someValue',
    value2 : 'anotherValue',
    //...
});

Also, I want to be able to wire-up specific events using "key words". For instance in jquery.UI you can call this to close a dialog

$('#myId').dialog('close');

My question is how do I setup my plugin so that it does one thing if it is being passed in the settings or it does other things depending on the keywords passed in? I tried looking at some of the jquery ui code but I'm not sure I understand what it's doing or even where to start to just pull out this functionality.

Upvotes: 0

Views: 646

Answers (2)

Matt Ball
Matt Ball

Reputation: 359816

Have a look at jQuery Plugins/Authoring, specifically Plugin Methods.

Example:

(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 );

Then...

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

Upvotes: 3

davin
davin

Reputation: 45525

check what type of object you're being passed:

if (typeof arguments[0] === 'string') {
 // I was given a string, my convention tells me this is a command
} else if (typeof arguments[0] === 'object') {
  // my convention tells me that this is an instantiation object
}

you might also want to check object properties, or use $.isArray()

Upvotes: 0

Related Questions