Создание вспомогательного модуля jQuery - PullRequest
2 голосов
/ 05 февраля 2011

Как написать вспомогательный плагин jQuery, чтобы я мог вызывать его с помощью $.myPlugin(), а не $.fn.myPlugin()?

С помощью плагина, созданного следующим образом, вы можете вызвать его только по $("selector").myPlugin() или $.fn.myPlugin().

(function( $ ){
  $.fn.myPlugin = function() {
  };
})( jQuery );

, где myPlugin() - вспомогательная функция, для которой не требуется ссылка this. Есть идеи?

Ответы [ 2 ]

3 голосов
/ 05 февраля 2011
(function( $ ){

  $.myPlugin = function() {

      var HelperDate1 = function() { ... };
      var HelperDate2 = function() { ... };
      var HelperMath1 = function() { ... };


      return {
             method1: HelperDate1,
             method2: HelperDate2,
             method2: HelperMath1

         };

  }();

})(jQuery);

Использование:

$.myPlugin.method1();
$.myPlugin.method2();

Но для этого вам не нужен jQuery.

РЕДАКТИРОВАТЬ:

var myHelper = (function($){

  var 
    pub = this,   //public
    pri = {};     //private


  // public method
  pub.HelperDate1 = function() {
        //...
  };

  pub.HelperDate2 = function() {
        //...
        pri._xFunctionPrivate2(); // can call private methods
  };

  pub.HelperMath1 = function() { 
        //... 
  };

  // public event method
  pub.InputEventClick = function(event) {
        //...
        // this is the element input, not the environment of the helper
        $(this).val("new value"); // example

  };

  // private method
  pri._xFunctionPrivate1 = function() { 
        //... 
  };

  pri._xFunctionPrivate2 = function() { 
        //... 
  };


  return public;

}).call({}, jQuery); //The first parameter is in context (this)

Использование:

myHelper.HelperDate1();
myHelper.HelperDate2();
$("input").bind("click", myHelper.InputEventClick);
myHelper._xFunctionPrivate1() // ERROR _xFunctionPrivate1 is private
2 голосов
/ 06 февраля 2011

@ andres предоставил одну из возможностей определения плагина jQuery, хотя более обычно вы определяете плагин, используя функциональность $.extend.

(function($) { // plugin closure

    var defaults = { ... };

    $.extend({
        myPlugin: function(options) { // when options are needed
            options = $.extend({}, defaults, options);
            // functionality afterwards
        }
    });
})(jQuery);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...