How do I write a jQuery helper plug-in so that I can invoke it with $.myPlugin(), as opposed to $.fn.myPlugin()?
With a plug-in created in the following way, you can only call it by $("selector").myPlugin() or $.fn.myPlugin().
(function( $ ){
$.fn.myPlugin = function() {
};
})( jQuery );
, where myPlugin() is a helper function that doesn't need the this reference. Any idea?
(function( $ ){
$.myPlugin = function() {
var HelperDate1 = function() { ... };
var HelperDate2 = function() { ... };
var HelperMath1 = function() { ... };
return {
method1: HelperDate1,
method2: HelperDate2,
method2: HelperMath1
};
}();
})(jQuery);
Use:
$.myPlugin.method1();
$.myPlugin.method2();
But you do not need jQuery for this.
EDIT:
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)
Use:
myHelper.HelperDate1();
myHelper.HelperDate2();
$("input").bind("click", myHelper.InputEventClick);
myHelper._xFunctionPrivate1() // ERROR _xFunctionPrivate1 is private
@andres has provided one of the possibilities of defining a jQuery plugin, though it's more usual that you define a plugin by using $.extend functionality.
(function($) { // plugin closure
var defaults = { ... };
$.extend({
myPlugin: function(options) { // when options are needed
options = $.extend({}, defaults, options);
// functionality afterwards
}
});
})(jQuery);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With