jQuery プラグインの型

メソッドを持つ jQuery プラグイン、毎回どう書くんだったかな、とぐぐることになるので、流用元となる型を記事にしておきます。

処理自体はコンストラクタ関数に持って、生成したインスタンスをdataに保持します。jQueryプラグインの役割は入口だけです。

window.jQuery && (function($){
	var PluginName = function(self, op){
		console.log('new!');
		this.self = self;
	};
	PluginName.prototype.method = function(op){
		console.log('method');
		console.log('op',op);
		console.log(this);
	};
	$.fn.pluginName = function(op) {
		return this.each(function(){
			var $this = $(this);
			if($(this).data('pluginName')){
				var method = op && typeof op == 'string' ? op : '';
				var method_arg = method && arguments.length > 1 ? arguments[1] : undefined;
				method && $(this).data('pluginName')[method] && $(this).data('pluginName')[method](method_arg);
			}else{
				var self = $this;
				op = op || undefined;
				$(this).data('pluginName',new PluginName(self, op));
			}
		});

	};
}).call(this,jQuery);

// セット時
$('.hoge').pluginName();
// セット時 オプション渡し
$('.hoge').pluginName({op1:1,op2:2});
// メソッド
$('.hoge').pluginName('method');
// メソッド オプション渡し
$('.hoge').pluginName('method',{op1:1,op2:2});

メソッドを.つなぎで書けるようにする(…できず)

$(‘.hoge’).pluginName.method();
のようにしたかったのですが、対象の要素を区別する必要がある場合は難しそうですね。

$.fn.pluginName.method = function(){ …
とした場合、method まで $(‘.hoge’) の情報が来なかった…。

$.fn.pluginName = function(){ …
の中で、
$.fn.pluginName.method = function(){ …
を指定して、thisを渡すと最後のもので上書きされてしまうし。

生成したインスタンスを  return してそれを変数に保持する形だと他のメソッドとの.つなぎができなくなるし。

…ということで私の今のスキルでは実装方法が思いつけず断念。