Alex Rivera | Logout

Public functions from within a jQuery plugin

Asked 2009-06-23T18:29:05.060
34

I love the jQuery plugin architecture, however, I find it frustrating (probably due to a lack of understanding on my part) when I want to retain a reference to the plugin instance to access properties or methods later on in my code.

Edit: I want to clarify that what I am really trying to do is retain a reference to the methods and properties used within the plugin, so that I can use them later

Lets take the case of a AJAX loading icon. In a more traditional OOP environment, I could do:

var myIcon = new AJAXIcon();
myIcon.start();
//some stuff
myIcon.stop();

The methods and properties of my object are stored on a variable for later use. Now if I want to have the same functionality in a jQuery plugin, I would call it from my main code somewhat like this:

$("#myId").ajaxIcon()

By convention, my plugin needs to return the original jQuery object passed to my plugin allowing for chainability, but if I do that, I loose the ability to access methods and properties of the plugin instance.

Now, I know that you can declare a public function in my plugin, somewhat along the lines of

$.fn.ajaxIcon = function(options) {
    return this.each(function () {
        //do some stuff
    }
}

$.fn.ajaxIcon.stop = function() {
    //stop stuff
}

However, without breaking the convention of returning the original jQuery object, I can't retain a reference to the specific instance of the plugin that I want to refer to.

I would like to be able to do something like this:

var myIcon = $("myId").ajaxIcon(); //myIcon = a reference to the ajaxIcon 
myIcon.start();
//some stuff
myIcon.stop();

Any thoughts?

Edit
Report

1 Answer

0

I think you could accomplish what you're looking for with something like this:

var myIcon = $("myId").ajaxIcon(); //myIcon = a reference to the ajaxIcon 
$.ajaxIcon.start(myIcon);//some stuff
$.ajaxIcon.stop(myIcon);

Haven't tested it though - I don't have access to an environment where I can do that atm

answered 2009-06-23T19:07:05.787

Your Answer