2015-09-07 84 views
0

這是我的jquery插件的結構。 我想知道如何我的代碼更改爲從插件jquery插件 - 公共方法結構

;(function ($, window, document, undefined) { 

/* Function-level strict mode syntax */ 
'use strict'; 

/* MYPLUGIN */ 
$.fn.myPlugin = function(options) { 
    var options = $.extend({}, $.fn.myPlugin.defaults, options); 

    return this.each(function() { 

     var $this = $(this); 
     var that = this; 

     //append overlay div 
     $(that).append("<div class=\"btn-overlay\"></div>"); 

     $(that).on('click', function() { 
      startEvent(); 
      setTimeout(function() { 
       endEvent(); 
      }, 2000); 
     }); 

     function startEvent() { 
      //code 
     } 

     function endEvent() { 
      //code 
     } 

    }); 
}; 

/* PLUGIN DEFAULTS PARAMETERS */ 
$.fn.myPlugin.defaults = { 
    //defaults 
}; 

})(jQuery, window, document); 

之外調用函數(stopEvent和startEvent)調用以這種方式

$('div').myPlugin(); 
$('div').myPlugin(startEvent); 
$('div').myPlugin(stopEvent); 

或調用這種方式

var plg = $('div').myPlugin(); 
plg.startEvent(); 
plg.stopEvent(); 

我想知道兩種調用方法有什麼區別。 感謝

回答

0

這是我認爲將是最適合你的結構:

;(function($,window,document,undefined) { 

    var Plugin = function(elem, options) { 
     this.elem  = elem; 
     this.$elem = $(elem); 
     this.options = options; 
     this.metadata = this.$elem.data('plugin-options'); //Support for inline settings. 
    }; 
    Plugin.prototype = { 

     //default options: 
     defaults: {}, 

     //Build: 
     init: function() { 
      //Store finall options - support for recursive extend: 
      this.config = this.config = $.extend(true, {}, this.defaults, this.options, this.metadata); 
      return this; 
     } 

     //methods: 
     methods: { 
      _method1 : function(){}, 
      _method2 : function(){} 
     } 
    }; 
    //Expose defaults: 
    Plugin.defaults = Plugin.prototype.defaults; 
    $.fn.plugin= function(options) { 

     //Append public methods: 
     this.method1 = function() { 
      this.each(function(i,e) { 
       $(e).data('plugin').methods._method1(); 
      }); 
     }; 

     //Support multi elements and add the indtance to data: 
     return this.each(function() { 
      if (undefined === $(this).data('plugin')) { 
       var plugin = new Plugin(this, options).init(); 
       $(this).data('plugin', plugin); 
      } 
     }); 

    }; 

    }); 

實例保存到元素data後的方法是可用的。

這部分掛鉤你想要的方式輕鬆訪問:

//Append public methods: 
this.method1 = function() { 
    this.each(function(i,e) { 
     $(e).data('plugin')._method1(); 
    }); 
}; 

所以結果是:

$('ele').plugin(options); 

//methods: 
$('ele').plugin.method1(); 
+0

這種結構的工作原理與同一頁面上的多個項目?例如ele = .class(多個元素)。謝謝 – Gus

+0

是的'返回this.each(函數(){...'將處理 –