I have a plugin which is applied on few element. Is there any way to store and retrieve JQuery plugin object so that we can run method of that object. A sample example is:
$('#li1').myPlugin(); // apply plugin object to different li
$('#li2').myPlugin(); // apply plugin object to different li
$('#li3').myPlugin(); // apply plugin object to different li
Now I want to retrieve the object from user activity on other external element, to run some method of the plugin. Like
var idx = 2
$('body').click(function(){ $('li').eq(2).highLight(); })
Since highLight is public method of myPlugin but not li, so it won’t execute.
Can I set myPlugin object as attribute to the element (but its not string) or can I do this way within plugin initialize,
$(this)[0].obj = this; // sounds weird.
What are the other option other than creating global associative array to store object with element Id as key. This is not possible in my case, as my plugin elements may or may not have Id.
EDIT
This is sample plugin, actual is too big to post here. Objective is to identify the plugin associated with element, by external activity. Sample example is using body.click but assume we cannot implement click inside my plugin. Actually events could be any external custom events which are not known to the plugin. I hope I am clear.
(function ($) {
$.fn.myPlugin = function (){
var ele = this;
// elr.get(0).extension = this; // can I do this, cross browser?
// so that later i can call it as
// $('li').eq(1).get(0).extension.highLight()
this.highLight = function(){
ele.css('color','red');
}
this.blueIt = function(){
ele.css('color','blue');
}
this.blueIt();
}
})(jQuery);
The two main alternatives are to use the
.data()jQuery method to store a reference to whatever you need, or use the convention of$(sel).pluginName("aMethod", anyData).I’ve never been a huge fan of the latter, but it’s common.