12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

glueコードを分離したjQueryのプラグイン作成方法

Last updated at Posted at 2016-01-15

jQueryのプラグインを作ろうと思うと、jQueryにプラグインを登録するコードが思い出せなくて、いつもググってしまう。というのも、jQueryプラグインの作成には、お決まりのボイラープレートコードを何行か書かないといけない。

普通にjQueryプラグインを作ろうとすると、プラグインの実装はボイラープレートコードに埋もれてしまう。

jquery.color.js
(function($) {
  $.fn.color = function(runtimeOption) {
    var defaultOption = {
      color: 'red'
    };
    var option = $.extend(defaultOption, runtimeOption);
    return this.each(function() {
      $(this).css('color', option.color);
    });
  };
})(jQuery);

だいたいこんな感じの実装になって、どこがjQueryとのglueコードで、どこがプラグインのロジックなのか分かりにくいし、こうしたコードだと数カ月後に新しいプラグインを作るときに、コピペしてどの部分を書き換えたらいいか考えないといけない。

jQueryに明示的なプラグイン登録APIが用意されていないため、こうした問題が起こる。

glueコードを分離したjQueryのプラグイン実装

こうした問題を手っ取り早く解決するために、jQueryとのglueコードとプラグインの実装を分けてコーディングするようにする。下のコードはaddPlugin関数がjQueryにプラグインを登録するための関数で、glueコードを隠蔽する。プラグインの実装は普通の関数にでき、addPluginにその関数を渡してjQueryと結合することができる。

// プラグインコード全体
(function($) {
  // jQueryとのglueコード
  function addPlugin(plugin) {
    $.fn[plugin.name] = function(runtimeOption) {
      var option = $.extend(plugin.option, runtimeOption);
      return this.each(function() { plugin.main.bind(this)(option); });
    };
  }

  addPlugin(/* プラグインの実装はここに書く */);
})(jQuery);

たとえば、文字色を変えるプラグインなら次のような感じのコードになる。

(function($) {
  function addPlugin(plugin) {
    $.fn[plugin.name] = function(runtimeOption) {
      var option = $.extend(plugin.option, runtimeOption);
      return this.each(function() { plugin.main.bind(this)(option); });
    };
  }

  // プラグインの実装
  addPlugin({
    name: 'color', // プラグイン名
    option: {color: 'red'}, // デフォルトのオプション
    main: function(option) { $(this).css('color', option.color); } // プラグインの実装
  });
})(jQuery);

このコードをCodePenで実行してみる

ちなみに、当然ながらプラグインを使う側のコードは、普通のプラグイン実装方法との違いは意識しなくていい。

// プラグインのクライアントコード
$('div:even').color();
$('div:odd').color({color: 'blue'}).css('background', 'pink'); // オプション指定したりメソッドチェーンも可
12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?