Can I get a reference to the object created in the jQuery plugin?

Maybe my brain is fried, but I'm writing a plugin that creates tweaks and also creates an object that I would like to access. So the plugin looks like this:

(function ($) {
  $.fn.myPlugin = function () {
    return this.each(function () {

          // do some stuff to the element...

          this.objectInstance = new usefulObject();

    });
  };
})(jQuery);

function usefulObject(){
    // useful object properties and methods....

    this.doSomething = function(){
        alert("Don't google Google. You'll break the internet.");
    }
}

      

so when I call the plugin I also want to access this useful object that I created. I thought that something like this might work.

tweakedElement = $("#someDiv").myPlugin();

tweakedElement.objectInstance.doSomething();

      

... but it doesn't work. How can I achieve this? Can I achieve this? Postcard answers or below, whichever suits you.

+2


a source to share


1 answer


You can save objectInstance

in the element in question using the jQuery function data

:

http://api.jquery.com/jQuery.data/



The jQuery.data () method allows us to attach data of any type to DOM elements in a circular-reference-safe and hence out of memory leak. We can set several different values ​​for one element and get them later

+1


a source







All Articles