# Dynamic call of module pattern function

I started reading about JavaScript patterns, and I really liked module pattern. So I created some module:

var App = (function (parent, $) { function myPrivateFunc () { // Some private stuff } return { myPubFunc: myPrivateFunc, publicFunction: function () { // Do some stuff } }; })(App || {}, jQuery);  Now I want to call some functions on page but only functions I need on that specific page. I got idea to add data-modules attribute to body, and then load modules I demanded on that attribute. I did that this way: var modules =$('body').data('modules').split(" ");

for (var i = modules.length - 1; i >= 0; i--) {
App[modules[i]]();
}


My question is: Is this a good way to achieve what I wanted? I tested, it's working fine, but I'm a little suspicious about this dynamic calling. Is there better solutions (preferably not libraries) out there? If this is not good, why it isn't?

-

## migrated from stackoverflow.comNov 26 '12 at 19:25

This question came from our site for professional and enthusiast programmers.

Instead of adding data-properties to the body tag, and waiting for / relying on jQuery, just use an inline script:

<script type="text/javascript">
var modules = /* echo the needed modules here */;
for (var i=0; i<modules.length; i++)
App[modules[i]]();
</script>

-
This is just another style of this logic, and i like it, but i prefer jQuery. My question is about logic, not the style. Anyway thanks. –  BenTalbert Nov 26 '12 at 16:38
What do you mean by "this logic"? What else did you have in mind? –  Bergi Nov 26 '12 at 17:13
By logic I mean on the way I'm calling functions. Is there better solutions for that. And is it my way secure? Does it affect on the speed? I read somewhere that i'm doing eval of whole script on this way, and that's bad. I don't know what that means. –  BenTalbert Nov 26 '12 at 17:22
Calling functions is just calling functions, and can't be done anyhow else. What does this have to do with security? And calling functions is slower than not calling functions, but which speed of what should be affected? And no, you are not evaling anything. –  Bergi Nov 26 '12 at 17:26
No, a loop is not slow; you won't recognize a difference to calling the modules successively (the loop might be inlined by the interpreter/compiler anyway :-). As you do not use eval, do not care about it. –  Bergi Nov 26 '12 at 17:42