开发者

Writing jQuery Plugins using OOP [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reope开发者_运维知识库ned, visit the help center for guidance. Closed 11 years ago.

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


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


Two links/templates I refer to are Stefan Gabos jQuery Plugin Boilerplate and Oscar Godson's jQuery Plugin Skeleton

I'm not claiming they're "state of the art" but they've served me very well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜