2011-06-23 4 views
1

一つはそうのようなjQueryプラグインを構築しているプラ​​グインの機能を公開:jQueryのは、私たちの古い開発者の

jQuery.fn.limelight = function(options) { 

/*Skipped code here*/ 

jQuery(".spotlight-btn.back a").click(function (e) { 

      if(lastSelectedCastIndex - 1 >= 0) { 
       removeFromSpotlight(); 
       lastSelectedCastIndex--; 
       e.preventDefault(); 
       $.address.value(lastSelectedCastIndex); 
       ca$t.scroll(jQuery.jcarousel.intval(lastSelectedCastIndex), true); 
       switchTo(lastSelectedCastIndex); 
      } 
      return false; 
     }); 

function switchTo(i) 
{ 
    ca$t.scroll(jQuery.jcarousel.intval(i), true); 
    $.address.title($("#title_text").text()); 
    putInSpotlight(); 
} 
}; 

私はjQueryプラグインのプログラミングを行っていませんでしたが、それは呼び出すことができるようswitchTo機能を公開したいと思いますどこでも。どのように私はこれを行うことができるでしょうか?最終};

答えて

3

これはおそらくあなたの目的のために過剰ですが、開発者がjQueryプラグインの目的を本当に理解しているか把握していないようです。

セレクタを受け入れることができ、イベント、スタイル、ダイナミックhtmlをセレクタ内の項目に適用することができるプラグインをやや汎用的にしたいとします。彼は単なる目的のために "プラグイン"を書いたようです...多分何らかの組織を維持するためかもしれません。

ほとんどのプラグインはこれと同様の形式に従います。http://docs.jquery.com/Plugins/Authoring

1

は、行を追加します。

+0

どのように単純です....グローバルスコープに移動するだけです。 – vsync

0

が一般的に利用可能な機能にするために、あなたの<script></script>タグ内switchTo()関数を貼り付ける前に、

window.switchTo = switchTo; 

0

あなたが公開することを可能にする、ステートフルなプラグインを作成するためのjQuery UIウィジェットファクトリーを使用することができます。

; (function ($) { 
    $.fn.limelight = function (method) { 
     var methods = { 
      //Initialize the plugin 
      init: function (options) { 
       return this.each(function() { 
       //Refactor to conform to plugin style 
//     $(this).click(function (e) { 
//      if(lastSelectedCastIndex - 1 >= 0) { 
//       removeFromSpotlight(); 
//       lastSelectedCastIndex--; 
//       e.preventDefault(); 
//       $.address.value(lastSelectedCastIndex); 
//       ca$t.scroll(jQuery.jcarousel.intval(lastSelectedCastIndex), true); 
//       switchTo(lastSelectedCastIndex); 
//      } 
//      return false; 
//     }); 
       }); 
      }, 

      switchTo: function (i) { 
      //Refactor to conform to plugin style 
//    ca$t.scroll(jQuery.jcarousel.intval(i), true); 
//    $.address.title($("#title_text").text()); 
//    putInSpotlight(); 

      } 
     }; 

     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.limelight'); 
     } 
    }; 
})(jQuery); 

//Following this pattern you'd be able to call your plugin like this. 
$(".spotlight-btn.back a").limelight(); 
$(".spotlight-btn.back a").limelight("switchTo", 0); 

ここで主題に関する公式文書ですプラグインがインスタンス化された後であっても使用されるパブリックメソッド(グローバルウィンドウ範囲を依然として回避する)

https://learn.jquery.com/plugins/stateful-plugins-with-widget-factory/

関連する問題