Writing jQuery Plugins Using Classes and Prototypes

后端 未结 3 1638
时光取名叫无心
时光取名叫无心 2021-01-30 09:44

Is it good or bad practise writing plugins this way(using class and prototypes), what are disadvatages of this code?

function PluginName(jqueryObject, options) {         


        
3条回答
  •  被撕碎了的回忆
    2021-01-30 10:28

    See the jQuery docs on plugin authoring for best practices:

    • Always wrap your plugin in (function( $ ){ // plugin goes here })( jQuery );
    • Don't redundantly wrap the this keyword in the immediate scope of your plugin's function
    • Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability.
    • Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults.
    • Don't clutter the jQuery.fn object with more than one namespace per plugin.
    • Always namespace your methods, events and data.

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

    Usage:

    $('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
    

    Defaults and Options Example

    (function( $ ){
    
      $.fn.tooltip = function( options ) {  
    
        var settings = {
          'location'         : 'top',
          'background-color' : 'blue'
        };
    
        return this.each(function() {        
          // If options exist, lets merge them
          // with our default settings
          if ( options ) { 
            $.extend( settings, options );
          }
    
          // Tooltip plugin code here
    
        });
    
      };
    })( jQuery );
    

    Usage:

    $('div').tooltip({
      'location' : 'left'
    });
    

提交回复
热议问题