Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have multiple instances of jQuery plugin on single page?

I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.

For instance, here is a sample plugin to illustrate my point:

(function($) {
  $.fn.samplePlugin = function(options) {
    if (typeof foo != 'undefined')
    {
      alert('Already defined!');
    } else {
      var foo = 'bar';
    }
  };
})(jQuery);

And then if I do this:

$(document).ready(function(){
  $('#myDiv').samplePlugin({}); // does nothing
  $('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});

This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.

I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?

Thank you for your guidance!

like image 461
James Skidmore Avatar asked Oct 23 '09 21:10

James Skidmore


1 Answers

I have the very same problem but i find a very handy solution i´ll post it for someone who may have this problem

when you define your variables insinde the plugin you could use the .data() to store all the variables you define

like this

(function($) {
  $.fn.samplePlugin = function(options) {
    var base = this;
    this.foo // define foo

    // do stuff with foo and other variables

    // Add a reverse reference to the DOM object
    this.data("pluginname", base);

  };})(jQuery);

And when you want to use the same foo variable you should retrive the reference with this:

base = this.data("pluginname");
base.foo

Hope it helps

Logan

like image 183
Logan Avatar answered Nov 01 '22 01:11

Logan