How to have member variables and public methods in a jQuery plugin?
jquery
Solution
I've found that the jQuery UI way of handling this seems to work out the best. You create your 'extra methods' as a string argument to your plugin:
$('#elem').autoCompleteEx('addItem', '1');
Then the 'this' context is preserved, and you can do something along these lines:
function addItem() {
// this should be == jquery object when this get called
}
$.fn.autoCompleteEx = function(options) {
if (options === 'addItem') {
return addItem.apply(this, Array.prototype.splice.call(arguments, 1));
}
};
Problem
I'm trying to create a jQuery plugin that will create something like an autoCompleteBox but with custom features. How do I store member variables for each matching jQuery element? For example I'll need to store a timerID for each. I'd also like to store references to some of the DOM elements that make up the control. I'd like to be able to make a public method that works something like: ``` $("#myCtrl").autoCompleteEx.addItem("1"); ``` But in the implementation of addItem() how can I access the member variables for that particular object like its timerID or whatever? Below is what I have so far... Thanks for any help or suggestions! ``` (function($) { //Attach this new method to jQuery $.fn.autoCompleteEx = function(options) { //Merge Given Options W/ Defaults, But Don't Alter Either var opts = $.extend({}, $.fn.autoCompleteEx.defaults, options); //Iterate over the current set of matched elements return this.each(function() { var acx = $(this); //Get JQuery Version Of Element (Should Be Div) //Give Div Correct Class & Add <ul> w/ input item to it acx.addClass("autoCompleteEx"); acx.html("<ul><li class=\"input\"><input type=\"text\"/></li></ul>"); //Grab Input As JQ Object var input = $("input", acx); //Wireup Div acx.click(function() { input.focus().val( input.val() ); }); //Wireup Input input.keydown(function(e) { var kc = e.keyCode; if(kc == 13) //Enter { } else if(kc == 27) //Esc { } else { //Resize TextArea To Input var width = 50 + (_txtArea.val().length*10); _txtArea.css("width", width+"px"); } }); }); //End Each JQ Element }; //End autoCompleteEx() //Private Functions function junk() { }; //Public Functions $.fn.autoCompleteEx.addItem = function(id,txt) { var x = this; var y = 0; }; //Default Settings $.fn.autoCompleteEx.defaults = { minChars: 2, delay: 300, maxItems: 1 }; //End Of Closure })(jQuery); ```