Public functions from within a jQuery plugin

If you do something like the following:

(function($){

$.fn.myPlugin = function(options) {
    // support multiple elements
    if (this.length > 1){
        this.each(function() { $(this).myPlugin(options) });
        return this;
    }

    // private variables
    var pOne="";
    var pTwo = '';
    // ...

    // private methods
    var foo = function() {
        // do something ...
    }
    // ...

    // public methods        
    this.initialize = function() {
        // do something ...
        return this;
    };

    this.bar = function() {
        // do something ...
    };
    return this.initialize();
}
})(jQuery);

Then you can access any of your public methods:

var myPlugin = $('#id').myPlugin();

myPlugin.bar();

This is taken from this very helpful article (May 2009) from trulyevil.com which is itself an extension on this article (Oct 2007) from learningjquery.com.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)