1

Below is my module pattern.

var Application = (function ($, window, undefined) {

}(jQuery, window));

Is there any way i can load my other Class/Object as params?. For instance, if i have a file named Helper.js inside Utils directory which by again is a module pattern. Can i pass it as a argument like below and use it in my Application class so that i can avoid usage of global variables in my class.

var Application = (function ($, window, undefined) {

}(jQuery, window, Helper));
theJava
  • 14,620
  • 45
  • 131
  • 172

2 Answers2

2

If you define your Helper as a local variable (using var), it will not clutter the global scope.

<script type="text/javascript">
    var Helper = (function() {
       var helper = { ... };
       return helper;
    }());
</script>


<script type="text/javascript">
    var Application = (function ($, window, helper) {

    }(jQuery, window, Helper));

<script>

Learn more about globals: Difference between variable declaration syntaxes in Javascript (including global variables)?

And a good tool to use for implementing the module pattern is to use a module loader, check out RequireJS

Community
  • 1
  • 1
Amy
  • 7,388
  • 2
  • 20
  • 31
  • Thanks, Just a question. There are two files Helper.js and Application.js. Can i still load Helper in Application.js. I am slightly getting confused here... – theJava May 14 '14 at 07:47
  • Yes they can be separate files, I'm just illustrating what the contents would be. It would be equivalent because the browser executes the JavaScript content as soon as it sees the ` – Amy May 14 '14 at 07:49
  • 1
    @theJava By the way, highly recommend using RequireJS because it takes care of the module variable scope and module dependency for you automatically. – Amy May 14 '14 at 07:51
  • At the end of the day all becomes local variables and can be injected and used in different files across. right? – theJava May 14 '14 at 08:04
1

This should be what you need, just pass it as a parameter of your module and stick it just before undefined, you can do it as many times as you need modules.

var Application = (function ($, window, Helper, undefined) {

}(jQuery, window, Helper));
axelduch
  • 10,769
  • 2
  • 31
  • 50