0

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.