4
\$\begingroup\$

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?

\$\endgroup\$
0
1
\$\begingroup\$

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>
\$\endgroup\$
6
  • \$\begingroup\$ 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. \$\endgroup\$
    – BenTalbert
    Nov 26 '12 at 16:38
  • \$\begingroup\$ What do you mean by "this logic"? What else did you have in mind? \$\endgroup\$
    – Bergi
    Nov 26 '12 at 17:13
  • \$\begingroup\$ 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. \$\endgroup\$
    – BenTalbert
    Nov 26 '12 at 17:22
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Bergi
    Nov 26 '12 at 17:26
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Bergi
    Nov 26 '12 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.