开发者

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

开发者 https://www.devze.com 2022-12-29 16:45 出处:网络
Perhaps my brain is fried, but I\'m writing a plugin that created an tweaks 开发者_JS百科an element, but also creates an object that i\'d like access to. So the plugin looks like this

Perhaps my brain is fried, but I'm writing a plugin that created an tweaks 开发者_JS百科an element, but also creates an object that i'd like access to. 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 be able to get access to that usefulObject that I created. I thought something like this might work....

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

tweakedElement.objectInstance.doSomething();

... but that's not working. How can I achieve this? Can I achieve this? Answers on a postcard, or down below, whichever suits you.


You can store objectInstance on the element in question using jQuery's data function:

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

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can set several distinct values for a single element and retrieve them later

0

精彩评论

暂无评论...
验证码 换一张
取 消