I've built a plugin that will use modules. Basically functions that can be added to the code in order to provide additional functionality.
In the plugin is a function to call these modules. Previously, I had called them like this:
processInstance($(doc).find('[data-bcp-crumbs]'), crumbs);
processInstance($(doc).find('[data-bcp-copyright]'), copyright);
processInstance($(doc).find('[data-bcp-activenav]'), activeNav);
The last part of each line is the name of a function that will be called within the processInstance script. So, I have the name of the function as both a string and a first-class object on each line. I would like to simplify that to something like this:
for (var i=0; i>module.length;i++) {
processInstance($(doc).find('[data-bcp-'+module[i].toLowerCase()+']'), window[module[i]]);
}
The module array is added to after each instance of the actual module code. I'm doing that like this:
module.push('crumbs');
This doesn't work because window[module[i]] is returning undefined.
How does my code need to be modified to make this work?
Here is an jsfiddle example of the entire plugin with a simple module inserted: http://jsfiddle.net/michaeljimmy/U8anp/1/
A colleague of mine helped me find the answer to this question. First, though, I noticed an error in the for loop. I had > instead of <. That didn't help. :)
The concept with the code was correct. The issue was scope. If you look at the jsfiddle, you'll see that the whole thing is in an enclosure, including the functions I was trying to call. So, there was no way window had access to the functions. We ended up making a couple simple changes.
First, along with module.push('crumbs'), or whatever the function name is, we added:
functions.crumbs = crumbs;
Then instead of using window[module[i]], we used
functions[module[i]]
Without the enclosure, window[module[i]] would have worked just fine.