ok am kinda new to plugins i have used many in my projects, i have also written basic plugins that just work on elements with options:
(function($){
$.fn
Following Samuel's answer, you can also use the following to avoid double handling the function names:
(function($) {
$.fn.myplugin = function(options, param) {
if( typeof(this[options]) === 'function' ) {
this[options](param);
}
// do default action
this.function1 = function() {
//do something
}
this.function2 = function(param) {
//do something else (with a parameter)
}
}
}
The addition of the param
variable allows you to call functions like below:
$.myplugin(); // does default behaviour
$.myplugin('function1'); // run function 1
$.myplugin('function2'); // run function 2
$.myplugin('function2',{ option1 : 4, option2 : 6 }); // run function 2 with a parameter object
See http://jsfiddle.net/tonytlwu/ke41mccd/ for a demo.
If you look at the design of some of the other jQuery plugins and jQuery UI, what they do is they have a single function $('#div').myplugin({options})
, and then they can do different functions by passing a string instead of an object $('#div').myplugin('performdifferenttask')
which can in turn call a helper function that is hidden from the user.
For an example look at http://jqueryui.com/demos/progressbar/#methods
Here is an example that will hopefully alleviate your confusion:
(function($) {
$.fn.myplugin = function(options) {
if(options == 'function1')
function1();
else if(options == 'function2')
function2();
else {
//do default action
}
}
function function1() {
//do something
}
function function2() {
//do something else
}
}
Then in use:
$.myplugin({option1: 4, option2: 6}); //does default behavior
$.myplugin('function1'); //calls function1()
$.myplugin('function2'); //calls function2()