Javascript Module Usage - javascript

I'm just getting started with javascript modules and I want to make sure I'm doing it correctly.
Below is an example of the methodology I'm following, based on the "Loose Augmentation Pattern" that I read about here
//myApp.js
var myApp = {};
//someModule1.js
(function (ma) {
ma.someModule1.DoStuff = function () {
alert("hi");
};
return ma;
}(myApp || {}));
//someModule2.js
(function (ma) {
ma.someModule2.DoMoreStuff = function () {
alert("ho");
};
return ma;
}(myApp || {}));
//someModule3.js
myApp.someModule1.DoStuff();
myApp.someModule2.DoMoreStuff();
The myApp variable within myApp.js would be the only variable that's globally exposed, with all of the other modules and their functions only being accessible via this variable.
someModule3.js isn't necessarily a module, but any arbitrary javascript wanting to access the properties of the myApp object (After the appropriate modules have been defined).
The part in particular I'm not 100% clear on is this: (myApp || {}, jQuery)
What is that part called and what exactly is it doing (I know the whole thing is a closure, but I just don't understand exactly how the last part is working)?
It seems like "ma" is initially nothing, I add a function to it in the body of the closure, then return ma. At this point myApp only has the one function.
In the bit at the end (myApp || {}), is it actually saying "ma isn't nothing, it's actually called myApp and I'll append those functions to that object if it exists."
Is that right or am I way off?

I see four issues:
Your code won't run as is. You have to define .someModule1 before you can assign to it.
There's no reason to do return ma because you aren't using the return value.
There's no reason to pass myApp || {} because if myApp is not defined, then your code will do nothing because the object you created would not be capture in any variable and will just be immediately garbage collected and not be accessible.
As you've shown your code, the IIFE you've enclosed the code in is not accomplishing anything other than adding lines of code and complexity.
Here's more detail on each issue.
Your modules won't run as is. You need to define .someModule1 by changing this and there is no reason in your code to pass myApp || {}:
//someModule1.js
(function (ma) {
ma.someModule1.DoStuff = function () {
alert("hi");
};
return ma;
}(myApp || {}));
to this:
//someModule1.js
(function (ma) {
// you must define .someModule1 before you can assign properties to it
ma.someModule1 = {};
ma.someModule1.DoStuff = function () {
alert("hi");
};
return ma;
}(myApp));
There is also no reason to do return ma in your code since you are not using the return value.
The reason myApp || {} is of no value here is because if myApp is not defined, then none of the code in your module does anything useful because the underlying object you would be assigning things to is not captured in a variable anywhere. So, if myApp is not defined, then your code accomplishes nothing. So, somewhat by definitino, myApp has to already be defined for your code to be useful, therefore, you can just pass myApp into the IIFE.
As you've shown the code, there is no benefit or reason to putting the assignment of properties inside the IIFE. You don't have any closure variables or anything that is private inside the IIFE. So, you would achieve exactly the same result with this:
myApp.someModule1 = {};
myApp.someModule1.DoStuff = function () {
alert("hi");
};
There are some reasons for using an IIFE, but you don't show any in this code example. Personally I'm a fan of using the simplest code that achieves your objectives and not adding extra complexity just for sake of it. Other people like to put all their code inside these IIFE modules. I only put my code inside an IIFE when there is actually a reason to have your code in an IIFE.

Related

Why wrap your angular controller code with anonymous function?

I've been seeing a number of people wrapping their controllers with:
function(){
//CODE
}();
What's the benefit / goal there?
That isn't really anything related directly to Angular, it is a JS pattern know as an Immediately Invoked Function Expression.
It is one of the most useful patterns in JavaScript, primarily because of:
Code Encapsulation
Since functions have closures in JS, we can use this pattern to create private data very easily:
var index = (function iife() {
var counter = 0; // <-- this is private, only available inside the closure of inner()
return function inner() {
return counter++;
};
})();
console.log(index()); // 0
console.log(index()); // 1
console.log(index()); // 2
console.log(index.counter) // undefined
We can also pass arguments into an IIFE, which allows us to control how we access the outside context of our IIFE. For example, to make sure $ is actually the jQuery object within your code:
(function ($) {
// here have access to the global jQuery as $ regardless of what window.$ is and
// how many libraries are trying to use $
})(jQuery);
By combining the two ideas above, IIFEs can also be used to implement the module pattern, which is the basis for how RequireJS and NodeJS separate code:
var myModule = (function iife(initData) {
// we can use initData here to initialize our module if necessary
var module = {};
// private vars ...
var privateVar1, privateVar2;
// private methods ...
function privateMethod() {
console.log('yeeey');
}
module.somePublicProperty = 1;
module.somePublicMethod = function() {
privateMethod();
};
return module;
})(/* pass initialization data */);
myModule.somePublicMethod(); // 'yeeey'
The reason you'll find a lot of JavaScript code wrapped in an anonymous function is to isolate it from other code on the page.
The following code will declare a variable called name on a global scope:
var name = "Hello World";
By using that code, any other script on the page attempting to use a variable called name could potentially get an unexpected value of "Hello World" because your script declared it as "Hello World".
By wrapping that code in an anonymous function, you keep the code from conflicting with other variables called name:
(function() {
var name = "Hello World";
})();
In the example above, name is now only available inside of the scope of the anonymous function. It is not global, and therefore cannot conflict with other code on the page.
By wrapping your Angular module in an anonymous function, you prevent your code from conflicting with other code.
Additionally, other people who may use your code won't have to worry about it changing their global scope.
IMHO it's not necessary, even superfluous, as most controllers are already functions:
'use strict';
angular.module('MyApp').controller('AboutController', ['$scope'
function ($scope) {
$scope.title = 'About Us';
}
]);
Everything #nem035 and #tcasey said is correct but it also have another side effect.
If you use tools like Grunt or Gulp it also allow you to have working dists to put in production.
If you do not use Immediate Invoke Pattern you'll most likely have minification problems like:
State X is already defined!
Unknown provider
. . .
I suggest you to wrap all your js modules with this pattern.
I hope I've been helpful.
There are many benefits of you immediately-invoked-function-expression short IIFE and it's best practice to use it. This way each of angular service or controller become isolate and you don't run into global variables as it can happened if you don't use IIFE.
read more about it

js - avoiding namespace conflict

Thus far I've worked only with relatively small projects (and mostly alone), but this time I have to collaborate with other programmers... basically because of that I must plan the structure of the website very carefully for the avoidance of spending hours debugging the code.
At this point I suppose doing that in the following manner. I divide my code in modules and store each module in a separate file inside an object (or a function) with a made-up name (lzheA, lzheB, lzheC etc.) to avoid conflicts whether an object with the same name was used in an another piece of code. When the document is loaded, I declare a variable (an object) that I use as a main namespace of the application. Properties of the object are the modules I defined before.
// file BI.lib.js
var lzheA = {
foo: function() {
},
bar: function() {
},
}
// file BI.init.js
function lzheK() {
BI.loadPage();
}
// file BI.loadPage.js
function lzheC() {
var result = document.getElementById('result');
result.innerHTML = "that worked";
}
// and so on
var lzheA,lzheB,lzheD,lzheE,lzheF,lzheG,lzheH,lzheI,lzheJ;
// doing the following when the document is loaded
var BI = {
lib: lzheA,
menu: lzheB,
loadPage: lzheC,
customScripts: lzheD,
_index: lzheE,
_briefs: lzheF,
_shop: lzheG,
_cases: lzheH,
_blog: lzheI,
_contacts: lzheJ,
init: lzheK,
}
BI.init();
https://jsfiddle.net/vwc2og57/2/
The question... is this way of structuring worth living or did I miss something because of lack of experience? Would the made-up names of the modules confuse you regardless of the fact that each one used only twice - while declaring the variable and assigning it to a property?
I consider the namespaces a good option when you want to modularize applications in Javascript. But I declare them in a different way
var myModule = myModule || {}; // This will allow to use the module in other places, declaring more than one specificComponent in other js file for example
myModule.specificComponent = (function(){
// Private things
var myVar = {};
var init = function() {
// Code
};
return {
init: init // Public Stuff
};
})();
If you want to call the init method, you would call it like this
myModule.specificComponent.init();
With this approach, i guarantee that the module will not be overwritten by another declaration in another place, and also I can declare internal components into my namespaces.
Also, the trick of just exposing what you want inside the return block, will make your component safer and you will be encapsulating your code in a pretty way.
Hope it helps

Are same name functions in different classes supported in Nodejs?

Can nodejs have two functions in different classes with the same name ?
If not then why not ? otherwise there is something wrong in the code.
Following is the example;
var admins = require('./routes/admins');
var users = require('./routes/users');
Both singleton classes
var users = function users(){
this.foo = foo = function(bar){ ...
}
}
users.getInstance = getInstance = function(){
if(this.instance == null){
this.instance = new users();
}
return this.instance;
}
module.exports = users.getInstance();
The admin class is also similar, both the classes have the same function names as well.
Now when foo is called it gets called of user class no matter what.
If i change the require order the foo of admin class is called.
As literally written in your question, I don't see a reason why this would happen. However, you are leaking into global scope, and that's how you might end up with duplicates.
users.getInstance = getInstance = function(){ ...
First, notice that the middle getInstance isn't scoped with var, so it gets assigned to the global scope. While this doesn't cause immediate problems, you're still polluting global scope, which is bad.
The real issue appears if you just do:
module.exports = getInstance();
Whether or not you've scoped getInstance with var, you're calling it in the global context, which means that inside the function, this == global. This means that the first time the function runs, it is basically doing:
global.instance = new users();
...and when your second file runs, it sees there's already a global.instance and just returns it.
Consider using 'use strict'; so these kinds of errors are caught for you.
Finally -- why are you doing all these getInstance gymnastics? They are entirely unnecessary. Your users file should just look like:
exports.foo = function(bar) {
...
};
Since the function name are same and the code is executed in sequential order, the function inside the second class overrides the first.
So the function will be called from whichever file is in second place.

Proper use of RequireJS, Coffeescript and Revealing Module Pattern

I have defined the following piece of Coffeescript code below, which defines a function using RequireJS:
define 'PersonService', ['jquery'] ($) ->
getPerson = (id) ->
person = dataService.GetPerson id
{ getPerson: getPerson}
It produces the following:
(function() {
define('PersonService', ['jquery'](function($) {
var getPerson;
getPerson = function(id) {
var person;
return person = dataService.GetPerson(id);
};
return {
getPerson: getPerson
};
}));
}).call(this);
I guess the issue I have is with the self-executing function that is produced from the Coffeescript code. Will this cause issues that I am possibly not tracking? Or is this proper.
Thank you.
It's correct
The difference between not having a wrapped function and having one is to do with scope.
If you define var a = 10; in the global scope a becomes global with or without the var keyword.
When wrapped all variables are local to the wrapped function so do not end up global.
In you example everything is already wrapped in a function so yes you don't need the extra wrapping!
You can tell coffee-script not to add the wrapper function using
coffee -b, --bare compile without a top-level function wrapper
IMHO: It's better to always have the wrapper function so you don't need to think about it on a file to file basis.

Defining Functions In Javascript Within jQuery

I'm working on a proprietary site, and I'm having some issues. I'm using jQuery along with prototype, and I've got it namespaced properly, so in this question assume you can use $ or jQ as a namespaced reference to jQuery.
So I've got a bunch of functions, some mix jQuery and javascript, some plain javascript, some jQuery only. Now, currently some functions are defined within the document.ready jQuery function, and some are defined outside of it, kind of like this:
jQ(document.ready(function($) {
if ( ifConfig ) {
//page check, function calls here
fnc1();
fnc2();
fnc3();
fnc4();
}
function fnc1() {
//fnc code in here
}
function fnc2() {
//fnc code in here
}
}); //end document.ready
function fnc3() {
}
function fnc4() {
}
Now this is all pseudo code, you can assume the functions are valid and have valid code in them. Recently I was doing some debugging, and one of my functions that was declared and called inside the document.ready said it was undefined. I moved it outside of the document.ready, and everything worked again.
I'm basically trying to understand the order of how functions are initiated/called better, so my question is when do you declare functions inside the document.ready and when do you declare them outside? Do you only declare inside when they're called within that document.ready only? Or should I always just declare them outside of that document.ready?
Thanks.
Generally, you should declare & define your own namespace, where all of your application logic (including functions/methods) is located. That way you avoid collision with other scripts on your site + that way your code is much cleaner and easier to maintenaine.
var myapp = function(){
var foobar1 = null,
foobar2 = null,
foobar3 = null;
return {
getFoobar1: function(){
return foobar1;
},
getFoobar2: function(){
return foobar2;
},
setFoobar1: function(foo){
foobar1 = foo;
},
clickhandler: function(e){
alert('I am an event handler, and I am not anonymous');
}
// etc.
};
};
$(document).ready(function(){
var Application = myapp();
Application.getFoobar2();
$(document).bind('click', Application.clickhandler);
});
That pattern (some call it the "method pattern") creates a closured function/object which also guarantees private member variables within your namespace, only accessible through the getter functions from the outside.
This is really only a pretty basic example, you can push this idea & pattern to an extend, which is very nice & a good thing (IMO).
A great book about this stuff which was named and recommended pretty often is "Javascript: The Good Parts" by Douglas Crockford.
If a function is only used inside the document ready function, then declare it inside so you don't pollute the global scope. Otherwise, declare it outside so it the rest of your script has access to those functions.
(document).ready is more used for things that need to be executed at page load, and not function declarations. If you declare them inside of (document).ready, their scope will be local to that block - if they're only used locally, that's fine and they should be declared there. Otherwise, declare them outside.
So in your example, if the functions are only used in that block, they should be declared in there. If they're used other places additionally, they should be declared outside.

Categories