I’m creating a jQuery plugin that needs to do a bunch of stuff the first time it is called (and only the first time). The first time I need to build an index out of a part of the dom, I would only like to do that once and use that index the rest of the time.
Ideally I want it to work like so:
- The first time it’s called, set run the function init() and set up all lots of var’s which I need in the whole plugin (so I can’t define them inside init() as they would be unavailable in the rest of the plugin).
- All the other times it is called it should use the vars already defined the first time.
First I tried this:
$.fn.search = function() {
if( !inited ) {
/*
Define everything that should only be defined the first time
*/
}
/*
All methods for my plugin, including an init() method
*/
if( !inited ) {
init();
var inited = true;
}
};
But I found out that every time the plugin is called all vars are gone, so that won’t work. I know I can store stuff like so:
$.fn.search.config = {
inited = false,
output,
search,
singleElems,
templates,
included,
scoreBoard,
container,
singles
}
And define them in init(), but is that the best way to store stuff for your plugin?
Use
data, that’s how most plugins do to store state and avoid duplicate initialization: