How to write jQuery plugin with Public Methods
The Code
(function($) { var methods = { hi : function(who) { who = who != '' ? "HI " + who + "!": "Who's there?"; alert(who); }, hello : function(who) { who = who != '' ? "Hello " + who + "!": "Who's there?"; alert(who); } }; $.fn.Say = function(method) { // do some checking on method request, if exist call it & pass any arguments to the function // else return error 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.ipt'); } }; })(jQuery);
How to use it
$(document).Say('hi','ahmad'); $(document).Say('hello','ahmad');
Reference: How to create a jQuery plugin with methods?
Reblogged this on Sutoprise Avenue, A SutoCom Source.