2015-10-25

javascript:jQueryプラグインの作り方

参考:

[1] http://d.hatena.ne.jp/cyokodog/20091126/define_plugin01
     -> 2.7 実装を prototype オブジェクトで定義
[2] http://logicbox.net/jquery/simplyscroll/

[3] https://gist.github.com/maepon/4754210[4] http://blog2.jamadam.com/?p=115


1.関数のプラグイン[1] -> 1.2 複数の関数を定義

  1. (function($){
  2. $.plugin = {
  3. hoge : function(){
  4. //...
  5. },
  6. fuga : function(){
  7. //...
  8. }
  9. }
  10. })(jQuery);





2.メソッドのプラグイン

[1] と[2]のsimlyscroll のコードを手本にした。


コンストラクタを作成し(下の例ではPlugin)、以下のテンプレートにはめ込んでプラグインを作成する。
[4]に公式な方法も載っているが、[2]でも使われているので、下記でも問題ないと思う。
尚、以下ではコンストラクタ雰囲気を残すために、myPluginでなく、Pluginとしてあるが、[1][2]では同じ名前を使っている。



プラグインコードのテンプレート
  1. (function($) { // 無名関数でラップしてプラグインを独立させておく。jQueryキーワードの代わりにドル記号($)を使用する。
  2. $.fn.myPlugin = function(opts) { // プラグインを定義する。
  3. return this.each(function() { // each();で回して全ての要素に対して同様に処理していく
  4. new $.Plugin(this,opts);
  5. });
  6. };
  7. var defaults = { // オプション(opts)のデフォルト値を定義
  8. opts1: 0,
  9. opts2: 0,
  10. //
  11. //
  12. };
  13. $.Plugin = function(elements, opts){ // コンストラクタの定義
  14. this.opts = $.extend({}, defaults, opts); // デフォルトオプションと渡されたオプションのマージ
  15. this.$id = $(elements); // などなど、中身を記載
  16. //
  17. //
  18. };
  19. $.extend($.Plugin.prototype,{ // プロトタイプを定義
  20. proto1: function() {
  21. //
  22. //
  23. },
  24. proto2: function() {
  25. //
  26. //
  27. },
  28. //
  29. //
  30. });
  31. })(jQuery);

プラグインの使用例
  1. $(function() {
  2. $("#id名").myPlugin({
  3. opts1: 800,
  4. //
  5. //
  6. });
  7. });