jQueryのプラグインを作ろうと思うと、jQueryにプラグインを登録するコードが思い出せなくて、いつもググってしまう。というのも、jQueryプラグインの作成には、お決まりのボイラープレートコードを何行か書かないといけない。
普通にjQueryプラグインを作ろうとすると、プラグインの実装はボイラープレートコードに埋もれてしまう。
(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);
ちなみに、当然ながらプラグインを使う側のコードは、普通のプラグイン実装方法との違いは意識しなくていい。
// プラグインのクライアントコード
$('div:even').color();
$('div:odd').color({color: 'blue'}).css('background', 'pink'); // オプション指定したりメソッドチェーンも可