I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other components. Both methods are effective, but the second option requires more code to achieve a similar outcome. I have heard about IIFE (http://en.wikipedia.org/wiki/Immediately-invoked_function_expression), but I am unsure of its advantages over my initial approach.
Is it not true that in the first method, everything is still contained within APP, thus avoiding pollution of the global namespace? Or should I opt for the second method for cleaner code?
What are the pros and cons of each approach?
Method 1:
<html>
<head>
<script type="text/javascript">
var APP = APP || {};
APP.homecontroller = {
index: function(){
APP.hometemplate.show();
}
}
APP.hometemplate = {
show: function(){
var x=document.getElementById("content");
x.innerHTML = "index content";
}
}
function init(){
APP.homecontroller.index();
}
</script>
</head>
<body>
<div id="content"></div>
<button onclick="init()">click to start</button>
</body>
</html>
Method 2:
<html>
<head>
<script type="text/javascript">
var APP = APP || {};
(function (APP) {
APP.homecontroller = (function () {
function index() {
APP.hometemplate.show();
}
return {
index: index
};
}());
APP.hometemplate = (function () {
function show() {
var x=document.getElementById("content");
x.innerHTML = "index content";
}
return {
show: show
};
}());
}(APP));
function init(){
APP.homecontroller.index();
}
</script>
</head>
<body>
<div id="content"></div>
<button onclick="init()">click to start</button>
</body>
</html>