Note that there are some explanatory texts on larger screens.

plurals
  1. POPublic functions from within a jQuery plugin
    primarykey
    data
    text
    <p>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.</p> <p><b>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</b></p> <p>Lets take the case of a AJAX loading icon. In a more traditional OOP environment, I could do:</p> <pre><code>var myIcon = new AJAXIcon(); myIcon.start(); //some stuff myIcon.stop(); </code></pre> <p>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:</p> <pre><code>$("#myId").ajaxIcon() </code></pre> <p>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.</p> <p>Now, I know that you can declare a public function in my plugin, somewhat along the lines of</p> <pre><code>$.fn.ajaxIcon = function(options) { return this.each(function () { //do some stuff } } $.fn.ajaxIcon.stop = function() { //stop stuff } </code></pre> <p>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.</p> <p>I would like to be able to do something like this:</p> <pre><code>var myIcon = $("myId").ajaxIcon(); //myIcon = a reference to the ajaxIcon myIcon.start(); //some stuff myIcon.stop(); </code></pre> <p>Any thoughts?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload