jQuery pluginの開発規約

2010/06/18

jQueryで効率よく開発する方法 jQuery pluginの開発規約について

1. Claim only a single name in the jQuery namespace 2. Accept an options argument to control plugin behavior 3. Provide public access to default plugin settings 4. Provide public access to secondary functions (as applicable) 5. Keep private functions private 6. Support the Metadata Plugin

■jQueryの名前空間には、ファンクションを一つのみ追加すること


$.fn.hilight = function() {

};

$('#myDiv').hilight();

■options引数を使って、アクセスできること


$.fn.hilight = function(options) {
  var defaults = {
     foreground: 'red',
     background: 'yellow'
  };
  var opts = $.extend(defaults, options);
};

$('#myDiv').hilight({
  foreground: 'blue'
});

extendについてはjQueryの継承(extend)参照

■デフォルト設定を、publicでアクセスできること


$.fn.hilight = function(options) {
    var opts = $.extend({}, $.fn.hilight.defaults, options);
};

$.fn.hilight.defaults = {
    foreground: 'red',
    background: 'yellow'
};

.defaultsという命名はマナー的なものでよいのかな?

■セカンダリーのファンクションにpublicでアクセスできること 自信のhtmlにstrongタグを追加する例


$.fn.hilight = function(options) {
    return this.each(function() {
        var $this = $(this);
        var markup = $this.html();
        markup = $.fn.hilight.format(markup);
        $this.html(markup);
    });
};

$.fn.hilight.format = function(txt) {'
    return '' + txt + '';
};

hilightにformatファンクションを追加している

■privateファンクションを保持する


(function($) {
    $.fn.hilight = function(options) {
        debug(this);
    };
    function debug($obj) {
        if (window.console && window.console.log)
        window.console.log('hilight selection count: ' + $obj.size());
    };
})(jQuery);

JavaScriptのクロージャで全体を囲んで隠蔽化

■Metadata Pluginのサポート クラス、ランダム属性、子要素とHTML5属性からメタデータを抽出するプラグイン jQuery Metadata

色々なプラグインライブラリもこのjquery.metadata.jsを利用しているものが多い。 jQueryの必須プラグインかも知れない。