I know I can create a self-invoking, nested function like this
(function ns(){
(function Class(){
alert('ns.Class fired');
})();
})();
But it's ugly, and doesn't look quite right.
My js chops aren't what they should be, and I'm hoping someone can show me a better way to structure my namespaced app and still be able to utilize "some" self invoking functions.
// THIS DOESN'T WORK
// because I haven't called "ns"
function ns(){
(function Class(){
alert('fired');
})();
};
For my purposes, the reason I'm asking this is to better namespace my JS in conjunction with jQuery.
So I'd like to be able to do something like this (which DOES WORK)
var ns = ns || {};
ns.Class = function(){};
ns.Class.Navigation = (function() {
$('#element').on('click', function() {alert('element clicked');});
})();
But I'm not sure if this is the right way to structure larger (read: js heavy) apps?!?!
Well, First off: the fact that your calling the "main" IIFE ns
suggests that you think of it as a namespace object, which isn't entirely correct. Namespaces are often created using IIFE's because they have the added benefit of closure scope(s). But in the end, namespaces are just a fancy word for Object (literals).
Take the most popular lib/toolkit/framework out there: jQuery. Basically, it's one huge IIFE, that constructs an equally vast object, that is assigned a number of methods and properties (well, references to function objects anyway). There are some other objects and variables created in that IIFE, but they are either not exposed to the global object at all, or (Very) indirectly.
Allow me to clarify:
var myNameSpace = (function()
{
var invisibleVar = 'can\'t touch this';
var objectLiteral = {sing: function()
{
return invisibleVar;//exposed, albeit indirectly
},
property: 'Hammertime'
};
var semiExposed;
objectLiteral.getSemi = function(newVal)
{
return semiExposed;//change closure var
};
objectLiteral.changeSemi = function(newVal)
{
semiExposed = newVal;//change closure var
};
objectLiteral.restoreSemi = (function(initVal)
{
return function()
{
semiExposed = initVal;//restore to value set when main IIFE was executed
//don't worry about what this references: use the force... of the scope
return objectLiteral.getSemi();//<-- return init val
};
}(semiExposed));//pass initial value to this scope
var notExposedAtAll = function()
{//can't be called but inside the main IIFE scope (and subsequent scopes)
objectLiteral.foo = 'But it adds a public property';
};
objectLiteral.changeMe = function()
{
notExposedAtAll();//called in default context (either null or global, but it doesn't matter here)
};
return objectLiteral;//direct exposure
}());
This uses some of the basic principals all toolkits/libs, and actually all decent JS scripts share: using functions as first class object, using them as expressions to create a temporary scope etc...)
IMO, it makes a good case for IIFE's: the scope gives you plenty of time to assign any object to a variable, so regardless of How you create a method (with or without an IIFE), you don't have to worry about what this
references at any given time, just use the variables.
You can implement some basic data hiding, too. In this example the initial value of semiExposed
is being passed to an IIFE, and preserved within its scope. Nothing can muck this up (well, that's not quite true at the moment), so you can allways revert to the initial values of any property.
However, I will admit, IIFE's can make your code harder to read as it grows, and I completely understand why you'd not want to use them too much. You could look into bind
, it'll help you cut back on many IIFE's, but there is a down-side. Some ppl still use IE8, for example, which doesn't support bind
.
But an other option would be: create a simple IIFE factory function:
function giveScope(varsFromScope,toFunction)
{
return function()
{
var passArguments = Array.prototype.slice.apply(arguments,[0]);//get args from call
passArguments.push({scope:varsFromScope});
toFunction.apply(this,passArguments);
};
}
var pseudoClosure = giveScope({scopeContext: this, something:'else'},function(arg1,arg2)
{
//function body here
arguments[arguments.length - 1].currentContext;//<== "closure scope"
this;//called context
});
That way, you can get rid of some IIFE's, by replacing them with a simple function call to which you pass an object. Easy, and X-browser compatible.
Lastly, your first snippet is something that I do tend to use in event delegation:
var target = e.target || e.srcElement;
var parentDiv = (function(targetRef)
{
while(targetRef.tagName.toLowerCase() !== 'div')
{
targetRef = targetRef.parentNode;
}
return targetRef;
}(target));
That way, I don't have to create another veriable in the same scope, my targetRef is assigned to parentDiv
when the div is found, and targetRef is GC'ed, I'm finished with it, so there's no need for that variable to stay in scope.
It's getting rather late now, and I don't know if I'm making much sense at all. Bottom line is: You might hate IIFE's, but you can't really do without them.
If it's the mass of parentheses that bother you, you might be glad to know that you don't have to use them. Any operator that forces the JS engine to interpret the function declaration as an expression will do:
(function()
{
}());
//can be written as:
!function()
{
}();
//or
~function()
{
}();
//or when assigning the return value, you don't even need anything at all:
var foo = function()
{
return 'bar';
}();
console.log(foo);//logs bar
Perhaps you prefer an alternative notations? But honestly: you may not like the syntax, but I'm afraid you're going to have to live with it, or switch to coffeescript or something.
$(function ns() {
"use strict";
(function Class(){
alert('ns.Class fired');
}());
});
ns is being passed to jquery object,and invocation occurs within function parens - passes the crockford test (jslint).
I'm trying to create a namespace for my backbone app so I can make calls globally. Normally, I'd just do it like this: var myNamespace = window.myNamespace || {}; myNamespace.SomeView = Backbone....
I'm trying to create a namespace for my backbone app so I can make calls globally. Normally, I'd just do it like this: var myNamespace = window.myNamespace || {}; myNamespace.SomeView = Backbone....
I am using this script to have a popup box with some setting in my site: http://codeissue.com/articles/a04daf3210c8b0a/cross-browser-modal-popup-using-javascript-jquery The popup opens when click a ...
I am using this script to have a popup box with some setting in my site: http://codeissue.com/articles/a04daf3210c8b0a/cross-browser-modal-popup-using-javascript-jquery The popup opens when click a ...
I have a very simple use case. I have an xhr object of ids of facebook users. Now I just want to display the images of the users in the following way. xhr.objects.forEach(function (user) { $('#...
I have a very simple use case. I have an xhr object of ids of facebook users. Now I just want to display the images of the users in the following way. xhr.objects.forEach(function (user) { $('#...
I am calling ipinfodb via JS. Recently I have had around 5-6 responses (from around 600) that specify the countryCode as 'RD'. 'RD' isn't a ccTLD and I cannot find any reason for this to be returned....
I am calling ipinfodb via JS. Recently I have had around 5-6 responses (from around 600) that specify the countryCode as 'RD'. 'RD' isn't a ccTLD and I cannot find any reason for this to be returned....