2011-06-23 69 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,無論是在選擇器中找到的項目都是有些泛型的。看起來他爲一個目的寫了一個「插件」......也許只是爲了維護某種組織。

大多數插件遵循類似於這樣一種形式:

; (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); 

下面是關於這個主題的官方文檔:http://docs.jquery.com/Plugins/Authoring

1

添加一行:

window.switchTo = switchTo; 

前的最後};

+0

多麼簡單....只是把它移到全球範圍。 – vsync

0

粘貼您的<script></script>標記內的SWITCHTO()函數,使之成爲一般可用的功能。