Initializing own plugins
- by jgauffin
I've written a few jquery plugins for my client. I want to write a function which would initialize each plugin which have been loaded.
Example:
<script src="/Scripts/jquery.plugin1.min.js")" type="text/javascript"></script>
<script src="/Scripts/jquery.plugin2.min.js")" type="text/javascript"></script>
<script src="/Scripts/jquery.initializer.min.js")" type="text/javascript"></script>
Here I've loaded plugin1 and plugin2. Plugin1 should be attached to all links with class name 'ajax' and plugin2 to all divs with class name 'test2':
$('document').ready(function(){
$('a.ajax').plugin1();
$('div.test2').plugin2();
}
I know that I can use jQuery().pluginName to check if a plugin exists. But I want to have a leaner way. Can all loaded plugins register a initialize function in an array or something like that which I in document.ready can iterate through and invoke?
like:
//in plugin1.js
myCustomPlugins['plugin1'] = function() { $('a.ajax').plugin1(); };
// and in the initializer script:
myCustomPlugins.each(function() { this(); };
Guess it all boiled down to three questions:
How do I use a jquery "global" array?
How do I iterate through that array to invoke registered methods
Are there a better approach?