Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing jQuery Plugins using OOP [closed]

I was wondering what's the current "state-of-the-art" to write a jQuery Plugins. I read a lot of different approaches and I don't know which one fits best.

Can you recommondation usefull links/templates for writing jQuery Plugins using OOP.

Thanks

like image 319
fabian Avatar asked May 08 '26 21:05

fabian


1 Answers

the basic rules are:

  1. Don't clutter the jQuery namespace with your code - there should only be one method per plugin added to root of the jQuery object or to jQuery.fn

  2. Use an immediately executing anonymous funciton to ensure the code is run just once

  3. Pass in the jQuery object as a parameter with the identifier $, can safely use the $ in this scope then :)

  4. REMEMBER when you add a new method to jQuery.fn, this is bound to a jQuery wrapped set, you don't have to wrap it again!

  5. use this.each to loop through all matched elements

  6. return this from your plugin to enable chainability (unless of course your plugin returns a distinct value)

  7. allow options to be passed in and overlayed over some default object (which you also expose to be overriden)

  8. allow for defaults to be re-set by user for global changes

    (function($) { //see point 3
    
        var defaults = {
           someDefaultValues : "value"
        };
    
        $.fn.myPlugin = function(options) { // see point 1, only 1 method
    
           var settings = $.extend({}, defaults, options); //see point 7
    
            this.each(function() { //see point 5
    
               var currentElement = $(this); //"this" now refers to current DOM element
               //put bulk of logic here
    
            });
    
            return this; //see point 6
        };
        //see point 8, enables users to completely override defaults, rather than per call via options
        $.fn.myPlugin.defaults = defaults; 
    
    })(jQuery); //see point 2
    

see the jQuery docs for a good guide, they go into more advanced details considering how you might want to execute more than one method per plugin, plus storing data on elements and other things. Most of the stuff i have

like image 59
WickyNilliams Avatar answered May 11 '26 12:05

WickyNilliams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!