Tom*_*ker 3 jquery jquery-plugins
如何编写 jQuery 帮助器插件,以便可以使用 来调用它$.myPlugin(),而不是$.fn.myPlugin()?
通过以下方式创建的插件,只能通过$("selector").myPlugin()或来调用$.fn.myPlugin()。
(function( $ ){
$.fn.myPlugin = function() {
};
})( jQuery );
Run Code Online (Sandbox Code Playgroud)
,其中myPlugin()是不需要this引用的辅助函数。任何想法?
(function( $ ){
$.myPlugin = function() {
var HelperDate1 = function() { ... };
var HelperDate2 = function() { ... };
var HelperMath1 = function() { ... };
return {
method1: HelperDate1,
method2: HelperDate2,
method2: HelperMath1
};
}();
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
使用:
$.myPlugin.method1();
$.myPlugin.method2();
Run Code Online (Sandbox Code Playgroud)
但您不需要 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)
Run Code Online (Sandbox Code Playgroud)
使用:
myHelper.HelperDate1();
myHelper.HelperDate2();
$("input").bind("click", myHelper.InputEventClick);
myHelper._xFunctionPrivate1() // ERROR _xFunctionPrivate1 is private
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1629 次 |
| 最近记录: |