1

私は以前に書いたシンプルな(軽量の)divスライダーを持っています。さまざまなプロジェクトで使用しているため、独自のプラグインにラップする時が来ました(軽量でなくなるリスクがあります! )。

これはプラグインチェリーをポップしているので、 http://docs.jquery.com/Plugins/Authoringを読んでコピーしていますが、(ほとんど)理にかなっていますが、何かが私を逃しています。ここに私のプラグインコードがあります:

(function( $ ) {

    //List of callable methods
    var methods = {
        init : function(options) {

            var settings = $.extend({

                optionOne   : 'aaa',
                optionTwo   : 'bbb',
                optionThree : 'ccc',
                optionFour  : 'ddd'

            }, options);        

        },

        error : function(message) {
            alert(message);            
        },        

        showSettings : function() { 
            //This bit... how to show whats in 'settings' defined in init?
        }

    }

    $.fn.ccSlider = function( method ) {

        //Calling methods
        if (methods[method]) {
            //If plugin is called with a recognised method, run that.
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if (typeof method === 'object' || !method) {
            //if plugin is called without a method, run the init() function
            return methods.init.apply( this, arguments );
        } else {
            //Run the error() function to catch all else.
            return methods.error("ccSlider: Method '"+method+"' does not exist!");            
        }
    };

})( jQuery );

ここにあるものはすべて期待どおりに機能していますが、必要なメソッドを書き続けることはできません。これは、init() メソッドの外部で「設定」の内容にアクセスする方法がわからないためです。

私はテストとして「showSettings」を使用していました...ポップアップして指定された設定の値(たとえば、optionTwo)が何であるかを教えてくれるshowSettingsメソッドをどのように記述しますか?

4

1 に答える 1

1

アーキテクチャは適切ですが、メソッドと設定は両方ともプラグインに対してグローバルである必要があります。

(function( $ ) {
   var defaults = {
        optionOne   : 'aaa',
        optionTwo   : 'bbb',
        optionThree : 'ccc',
        optionFour  : 'ddd'
   } //if there are any

   var settings = {}; //you can reach the settings from any where in your plugin now
   //List of callable methods
   var methods = {
      init : function(options) {
         //initialize the settings in your init function and you are good to go
         settings = $.extend({},defaults,options);        
      },

      error : function(message) {
        alert(message);            
      },        

      showSettings : function() { 
        //This bit... how to show whats in 'settings' defined in init?
      }

  }

  //your plugin code here like in your post but now you can use the settings variable      we defined in your plugin
});
于 2012-04-06T21:10:08.137 に答える