1

I understand that using closures (IIFE) is the best practice as it prevents polluting the global namespace. However, when I added the closures to my files, it prevented my 2nd file (controllers.js) from reading the first file (models.js). To give you an idea, here's what they look like:

models.js

;(function() {
  function searchResult (obj) {
    this.state = obj.State;
    /*Do more stuff */
  }

})();

controllers.js

;(function() {
 function storeSearchResults(jsonObj) {
   var instance = new searchResult(jsonObj.data[i]);
   /* Do more */
 }     
})();

Now that I've added closures on them, I'm getting an error that searchResult is undefined in controllers.js -- because it can't see that it exists in the models.js. How do I get it to understand that it exists in the other file?

P.S. Yes, models.js is added in the HTML file before the controllers.js file.

1

2 Answers 2

3

For them to interact, they have to have some common symbol. You have a couple of choices:

  1. Do it yourself (using a single global variable)

  2. Use some kind of library that does it for you (using [ideally] just a single global symbol)

  3. Do it yourself a different way that requires no global common symbol at all

Do it yourself

The DIY version is, typically, that you have a single global, for your entire app, which your various modules add properties to.

So for instance:

models.js:

;(function(globals) {
  var MyApp = globals.MyApp = globals.MyApp || {};
  MyApp.searchResult = searchResult;
  function searchResult (obj) {
    this.state = obj.State;
    /*Do more stuff */
  }

})(this);

That works because in loose mode, this at global scope is the global object (window on browsers). We pass it into the IIFE as the argument globals, and then either use or create a property on it called MyApp, and add searchResult to it as a property.

controllers.js:

;(function(globals) {
  var MyApp = globals.MyApp = globals.MyApp || {};
  function storeSearchResults(jsonObj) {
    var instance = new MyApp.searchResult(jsonObj.data[i]);
    /* Do more */
 }     
})(this);

We do the same thing, except that controllers.js is expecting that models.js has already been run. Although we still do the var MyApp = globals.MyApp = globals.MyApp || {}; bit, the new MyApp.searchResult would of course fail if models.js hadn't been run.

There are probably a dozen syntactic variations on this theme, this is just one of them.

Use some kind of library that does it for you

Your other option is to use a library like RequireJS (the one global symbol there is require, and it's a function) or any other asynchronous module definition lib.

Do it yourself another way

Another DIY option gets rid of globals entirely, you don't even need a single global.

To do that, your individual files don't have the IIFE (although they can use ones for things they don't want to share with other files):

;
function searchResult (obj) {
  this.state = obj.State;
  /*Do more stuff */
}

controllers.js:

;
function storeSearchResults(jsonObj) {
  var instance = new searchResult(jsonObj.data[i]);
  /* Do more */
}

Then you use a minifier to combine your scripts and wrap them in one big IIFE. You might have pre.js:

(function() {

and post.js:

})();

Then the minifier creates app.js by combining pre.js + models.js + controllers.js + post.js. The end result (un-minified and formatted here for readability) is:

(function() {
    ;
    function searchResult (obj) {
      this.state = obj.State;
      /*Do more stuff */
    }

    ;
    function storeSearchResults(jsonObj) {
      var instance = new searchResult(jsonObj.data[i]);
      /* Do more */
    }
})();

I called this DIY, but I wouldn't be surprised if there were tools to help with it.

8
  • Thanks @TJ, your solved my issue! Two questions that I have for the sake of understanding are: 1.) What is the (this) argument at the end of each IIFE for? and 2.) How is controllers.js able to understand where to get the global parameter from -- since no one is explicitly calling it?
    – ayjay
    Jun 21, 2014 at 19:26
  • 1
    @ayjay: At the top level of a script block, if you are not using "use strict", this is the global object (aka window on browsers; technically, window is a property on the global object -- a global variable -- that it uses to refer to itself). So by passing this into our IIFE, we can reference it with the argument name global. (I would typically use "use strict" at the top of the IIFE, so that the code within the function was strict mode, as strict mode is quite handy. But outside the IIFE, I like to use this rather than window, as it's not browser-specific. Jun 21, 2014 at 20:28
  • Thanks, and I have a Follow up question... is there a reason why you chose a 3-level deep definition (i.e., global.MyApp.searchResult) as opposed to 2 (i.e., global.searchResult? I'm wondering if using 3-level is a best practice approach.
    – ayjay
    Jun 23, 2014 at 1:34
  • @ayjay: It's so we only have one global: MyApp. I think my naming of the argument in the code above was really confusing (I used global as in "the global object" which is what contains global variables), so I've changed it to globals (because the "global object" contains global variables). Also, I added a var MyApp = in front of the bit that sets up globals.MyApp so we can use MyApp within the IIFE. Updated pastie as well: pastie.org/9315636 Any property we put on globals becomes a global variable, so we want to keep that to a minimum (zero if possible, one in the above). Jun 23, 2014 at 7:18
  • I have another question that's related to the response you've provided (btw, I really appreciate all the responses). When dealing with namespaces between files, which approach is more commonly used: Approach A OR Approach B? I understand both works, but am curious which convention is more followed in the real world.
    – ayjay
    Oct 12, 2014 at 22:17
-2

Events and listeners passing and receiving data.

I don't use globals.

However I don't know how to use events in raw javascript or if data passing can be done. I use jquery/node which allow for passing data and just works beautifully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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