Reputation: 755
I use self invoking functions to include all the javascript code inside an angular controller (I think I saw it somewhere as a best practice). So my controller looks like this:
(function() {
// code
})()
I use gulp to merge all the controllers into one file. My question is this. Does this mean that all of my Javascript code will be invoked and executed when my application starts? If so, I guess that this is not a very good approach. Are there any solutions to that issue? Any comments? Thanks
Upvotes: 1
Views: 3383
Reputation: 12558
No, not all the code gets executed. When you define your Angular modules
(function() {
'use strict';
angular
.module('myModule', [])
.controller('myController', ['$http', myControllerFunc]);
function myControllerFunc ($http) {
// ...
}
})();
what gets executed are only the angular
methods to register the module and the controller. But the actual controller logic is in the callback function, and that gets only called when the controller is invoked (e.g. by the router).
So, its all good, and wrapping the code in anonymous functions is a good idea to keep, for example myControllerFunc
, out of the global namespace.
Upvotes: 5
Reputation: 3576
It does not matter wether you define your code into an anonymous function. Javascript client ( browser for this matter ) will have to parse your code either way.
So if you have something callbable in the anonymous function, it will get executed. If you have a declared var with decoupled methods, it will just define that var, just like it would do in a simple separated script inclusion.
Javascript is "parsing" your javascript either way, but will never call methods that are not called by your code. Of course it needs to know that when you call foo( bar )
that foo
exists, so it will parse it. It's common javascript.
Upvotes: 1