5

アクセス可能なメソッドとオプションを備えたプラグインを構築したいと考えています。これは複雑なプラグイン用です。プラグインの外部でメソッドにアクセスできるようにする必要があります。これは、誰かが DOM に何かを広告した場合、それを更新する必要があるためです (したがって、完全なプラグインを再度実行する必要はありません)。

過去にこのようなプラグインがあるのを見たことがありますが、それらを見つけることができないので、それらを見ることはできません. 私はまだjavascriptに慣れていないので、どんな助けでもいいでしょう。

オプションをグローバルにオーバーライドできると便利です。

プラグインの使用方法:

// options
$('#someid').myplugin({name: 'hello world'});

// methods(would be nice if we can use this)
$('#someid').myplugin('update');

// 古いプラグイン ラッパー

;(function($, window, document, undefined){

    $.fn.pluginmyPlugin = function(options) { 

        options = $.extend({}, $.fn.pluginmyPlugin.options, options); 

            return this.each(function() {  

                var obj = $(this);

                // the code 
            });     
        };

        /**
        * Default settings(dont change).
        * You can globally override these options
        * by using $.fn.pluginName.key = 'value';
        **/
        $.fn.pluginmyPlugin.options = {
            name: '',
                            ...         
        };

})(jQuery, window, document);

アップデート

したがって、jQuery のドキュメントを参照した後、次のコードを作成しました。コードに何か問題がある場合はお知らせください。

;(function($, window, document, undefined){

    var methods = {

        init : function( options ) {

            options = $.extend({}, $.fn.pluginmyPlugin.options, options); 

            return this.each(function(){

            alert('yes i am the main code')

            });
        },
        update : function( ) {
             alert('updated')
        }
    };

    $.fn.pluginmyPlugin = function(method) { 

        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 this plugin' );
        }    

    };

        /**
        * Default settings(dont change).
        * You can globally override these options
        * by using $.fn.pluginName.key = 'value';
        **/
        $.fn.pluginmyPlugin.options = {
            name: 'john doe',
            //....
        };

})(jQuery, window, document);
4

4 に答える 4

3

別の方法:

var Plugin = function($self, options) {
  this.$self = $self;
  this.options = $.extend({}, $.fn.plugin.defaults, options);
};

Plugin.prototype.display = function(){
  console.debug("Plugin.display");
};

Plugin.prototype.update = function() {
  console.debug("Plugin.update");
};

$.fn.plugin = function(option) {
  var options = typeof option == "object" && option;

  return this.each(function() {
    var $this = $(this);
    var $plugin = $this.data("plugin");

    if(!$plugin) {
      $plugin = new Plugin($this, options);
      $this.data("plugin", $plugin);
    }

    if (typeof option == 'string') {
      $plugin[option]();
    } else {
      $plugin.display();
    }
  });
};

$.fn.plugin.defaults = {
  propname: "propdefault"
};

使用法:

$("span").plugin({
  propname: "propvalue"
});

$("span").plugin("update");

これは、 Twitter Bootstrap の JavaScript テンプレートにばかげて似ています。しかし、そこから完全に取っていたわけではありません。を使用してきた長い歴史があり.data()ます。

適切にラップすることを忘れないでください。

于 2012-12-08T13:44:01.210 に答える
1

jQuery UI Widget Factoryを試しましたか?

少し学習曲線がありましたが、今では気に入っています。オプションを処理し、デフォルトとメソッドを許可し、すべてを非常に凝ったものにまとめています:)


編集

jQuery UI Widget Factory は、ステートフルな jQuery プラグインを作成するための簡単なオブジェクト指向の方法を提供する、jQuery UI ライブラリの個別のコンポーネントです。

ステートフル プラグインとウィジェット ファクトリの紹介.

余分なオーバーヘッドは、ほとんどの状況で心配する必要はないと思います。最近、私は coffescript で書いており、すべてがコンパイルされ、縮小され、gzip されているため、あちこちにいくつかの行が追加されても、大きな違いはありません。Web サイトの速度に関する私の調査では、HTTP 要求の数が重要であることを示しているようです。実際、私をこのトラックに乗せた元同僚は、ブラウザ ベースのゲームで働いていて、速度速度がすべてでした。

于 2012-12-08T13:02:57.797 に答える