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
精彩评论