最終更新:2011-10-15 (土) 15:50:30 (4570d)  

jQuery/プラグイン/開発

http://docs.jquery.com/Plugins/Authoring

例1

//他のライブラリとコンフリクトしないようにクロージャを使う
(function( $ ){
	$.fn.関数名=function(options){
		//デフォルトパラメータ。マージされる
		var options = $.extend({
			hoge:"huga"
		}, options);
		// thisが既にjQueryオブジェクトなので $(this) にする必要はない
		// $(this) は $($('#element'));と同じ

		this.each(function() {
			//なんか処理
		});

		//return valueで値を返してもよい
		return this;//メソッドチェーンするときはthisをreturn
		/*
		return this.each(function(){
			//メソッドチェーンの時はeachの結果をreturnしても良い
		});
		*/
	});
})( jQuery );

例2

//他のライブラリとコンフリクトしないようにクロージャを使う
(function( $ ){
	//プラグイン内で使うメソッドを宣言
	var methods = {
		init : function( options ) { // THIS },
		show : function( ) { // IS   },
		hide : function( ) { // GOOD },
		update : function( content ) { // !!! }
	};
	$.fn.tooltip = function( method ) {

	// Method calling logic
	if ( methods[method] ) {
		//指定されたメソッドが存在していたらそれを呼ぶ
		return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
	} else if ( typeof method === 'object' || ! method ) {
		//指定されたメソッド(引数)がオブジェクトだったら初期化
		return methods.init.apply( this, arguments );
	} else {
		$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
	}    

	};
})( jQuery );
$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

jQuery plugin refactoring

参考

関連