artimys
4/14/2017 - 5:23 PM

jQuery Plugin Boilerplate

// -------------------------------------------------------------
// SKELETON
// Adding IIFE (Immediately Invoked Function Expression) around $.fn.
// to protect $ from getting overriden by other JS libraries
// -------------------------------------------------------------
;(function ( $, window, undefined ) {
  $.fn.myPlugin = function() {
    
    // there's no need to do $(this) because
    // "this" is already a jquery object
    // $(this) would be the same as $($('#element'));

    this.fadeIn('normal', function(){
      // the this keyword is a DOM element
    });
    
  };
  
  
  
}(jQuery, window));


// -------------------------------------------------------------
// DEFAULTS AND OPTIONS
// -------------------------------------------------------------
(function( $ ){
  $.fn.tooltip = function( options ) {  

    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
      'location'         : 'top',
      'background-color' : 'blue'
    }, options);

    return this.each(function() {        
      // Tooltip plugin code here
    });

  };
})( jQuery );


// This is a common plugin development pattern.
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
// Merge defaults and options, without modifying defaults
var settings = $.extend( {}, defaults, options );
// Results
defaults -> {"validate":false,"limit":5,"name":"foo"}
options  -> {"validate":true,"name":"bar"}
settings -> {"validate":true,"limit":5,"name":"bar"}
# A class-based template for jQuery plugins in Coffeescript
#
#     $('.target').myPlugin({ paramA: 'not-foo' });
#     $('.target').myPlugin('myMethod', 'Hello, world');
#
# Check out Alan Hogan's original jQuery plugin template:
# https://github.com/alanhogan/Coffeescript-jQuery-Plugin-Template
#
(($, window) ->

  # Define the plugin class
  class MyPlugin

    defaults:
      paramA: 'foo'
      paramB: 'bar'

    constructor: (el, options) ->
      @options = $.extend({}, @defaults, options)
      @$el = $(el)

    # Additional plugin methods go here
    myMethod: (echo) ->
      @$el.html(@options.paramA + ': ' + echo)

  # Define the plugin
  $.fn.extend myPlugin: (option, args...) ->
    @each ->
      $this = $(this)
      data = $this.data('myPlugin')

      if !data
        $this.data 'myPlugin', (data = new MyPlugin(this, option))
      if typeof option == 'string'
        data[option].apply(data, args)

) window.jQuery, window