jQuery プラグインを作成するには、新しい関数プロパティを jQuery.fn オブジェクトに追加することから始めます。ここで、プロパティの名前はプラグインの名前です。
jQuery.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
上記は最も簡単なプラグイン作成です。$
従うべき特定の手順がありますが、mootools、prototype などの他のライブラリとのドル記号の競合を避けるために、クロージャを使用することがベスト プラクティスです。
プラグインがドル記号を使用する可能性のある他のライブラリと衝突しないようにするため、jQuery をドル記号にマップする IIFE (Immediately Invoked Function Expression) に渡して上書きできないようにすることをお勧めします。実行範囲内の別のライブラリによって。
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})(jQuery);
そのクロージャ内で、jQuery の代わりにドル記号を好きなだけ使用できます。
名前空間:
プラグインの名前空間を適切に設定することは、プラグイン開発の非常に重要な部分です。名前空間が正しく設定されていると、プラグインが他のプラグインや同じページに存在するコードによって上書きされる可能性が非常に低くなります。名前空間は、メソッド、イベント、およびデータをより適切に追跡できるため、プラグイン開発者としての作業も楽になります。
プラグイン メソッド
(function( $ ){
$.fn.tooltip = function( options ) {
// THIS
};
$.fn.tooltipShow = function( ) {
// IS
};
$.fn.tooltipHide = function( ) {
// BAD
};
$.fn.tooltipUpdate = function( content ) {
// !!!
};
})(jQuery);
$.fn
名前空間が乱雑になるため、これは推奨されません。これを解決するには、プラグインのすべてのメソッドを に集め、メソッドobject literal
の文字列名をプラグインに渡して呼び出す必要があります。
(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 );
// calls the init method
$('div').tooltip();
// calls the init method
$('div').tooltip({
foo : 'bar'
});