2011-02-05 80 views
2

如何編寫jQuery幫助程序插件以便我可以用$.myPlugin()而不是$.fn.myPlugin()來調用它?創建jQuery幫助程序插件

通過以下方式創建插件,您只能通過$("selector").myPlugin()$.fn.myPlugin()來調用它。

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

,其中myPlugin()是不需要this參考一個輔助功能。任何想法?

回答

2

@andres提供的定義jQuery插件的可能性之一,雖然它是更常見的是通過使用$.extend定義插件功能。

(function($) { // plugin closure 

    var defaults = { ... }; 

    $.extend({ 
     myPlugin: function(options) { // when options are needed 
      options = $.extend({}, defaults, options); 
      // functionality afterwards 
     } 
    }); 
})(jQuery); 
3
(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 
+1

你是什麼意思*他不需要jQuery這個*? – 2011-02-06 07:28:21