オプション付きjQueryプラグインの最小構成テンプレート
// オプション付きの実行コード
jQuery(function($) {
$("#selector").myPlugIn({
opt1 : 100,
opt2 : "Love is Danger"
});
});
// オプションを省略した実行コード
jQuery(function($) {
$("#selector").myPlugIn();
});
/* 先頭行: 他のスクリプトでのセミコロン忘れに備え、且つ、予約語でないundefinedの書換えによる誤動作を防いでいる。*/
;(function($, undefined) {
"use strict";
$.fn.myPlugIn = function(option) {
var a, b, c;
//※未設定のオプション項目に初期値を設定
option = $.extend({
opt1: null,
opt2: null
}, option);
//※プラグイン内部でのみ使用される関数
function DoSomething(e) {
}
//※対象要素群のそれぞれに対し何かする
this.each(function() {
DoSomething($(this));
});
//※外部から参照可能な関数
$.fn.publicMethod = function( options ) {
//
};
// 何かする
return this; //※メソッドチェーン対応の為に return しておく
};
})(jQuery);
/* 最終行: 第二引数は指定しない。undefined が 先頭行の undefined 引数に設定される */