views:

76

answers:

2

Hello,

I am writing my first jQuery plugin and I want to be able to do this:

var myPluginVar = $("someElement").myPlugin();

myPluginVar.customFunctionCallWithinPlugin();

Any idea how to go about it?

EDIT

Please visit http://flowplayer.org/tools/using.html#api to see what i mean

+1  A: 

You could achieve this design with something similar to the following. I have wrapped the plugin definition within a closure to keep PluginObj from polluting the global namespace.

(function($) {
    function PluginObj() {
        // construct stuff
    }

    PluginObj.prototype.customFunctionCallWithinPlugin = function() {
        // do stuff
    };

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

The jQuery method returns a new object with the methods you define. This is a non-standard design for a jQuery plugin though, so if you plan to distribute it make sure it is thoroughly documented.

Alex Barrett
+1. You beat me to it.
David Murdoch
+1  A: 

You may have to return an instance of the plugin rather than "this".

e.g.

(function(){
    // private constructor that is only accessable by your plugin.
    function _Plugin(elements, args){
        // do stuff
    }
    _Plugin.prototype.customFunctionCallWithinPlugin = function(){
        // do more stuff
    };
    $.fn.Plugin = function(args){
        return new _Plugin(this, args);
    };
})();

EDIT: Alex beat me to it.

David Murdoch
The similarity of our comments is quite astounding. Have a +1 yourself :d
Alex Barrett
Thanks guys!!! Alex i checked yours but I'll use David's :)
chchrist