How to make jQuery plugin work with several elements at the same time?

I created a combobox plugin. To use it, you just need to call

$(elem).combobox(compensateElement); 

EDIT: The problem is that if you do

 $('#1').combobox('form'); $('#2').combobox('form'); 

the plugin will break ...

An element is a choice to be converted into a combo box, and the compensation parameter value is an element after which the plugin can insert a div that is the maximum length of tipsDiv-20px. (I have a footer on my page that is not reset by absolute positioned elements ...)

Now the problem is that this plugin can ONLY BE USED ON ONE ITEM! How can it be changed so that it can work with several elements at once? This is more than a hundred lines of JS code, so I do not expect "converted" code!

I thought about putting all the element-specific variables into the this.data object, but it did not feel at all like a good solution. After running some RegEx find & replace it and setting it up for a couple of hours, I didn't get it to work at all ...

What methods can i use?

Thanks so much for your time!

+6
source share
2 answers

The problem is that you have a literal object that will replace its contents every time you call m.init() .

I suggest you look at this post , which explains good approaches to writing jQuery plugins. If you see Easy Start, for example:

 $.fn[pluginName] = function ( options ) { return this.each(function () { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin( this, options )); } }); } 

this creates a new instance of the plugin object for each element, so you can maintain state sequentially.

+10
source

you can call your plugin methods for each element using every jQuery function. Remember that inside your methods, the this will point to the current element, not the jQuery object.

  $.fn.combobox = function(form) { var $this = this; return $this.each(function () { if (!m.initialized) { m.init.apply(this, [form]); $this.data('initialized', true); } else { m.updateList.apply(this); } }); }; 
0
source

All Articles