Javascript Closures are not working? - javascript

I'm trying to implement clojure in javascript. Can anyone see what the problem is?
var a = (
function()
{
var privateFunction = function()
{
alert('Hello');
}
var OsmanFunction = function()
{
alert('Osman');
}
return
{
publicFunction: function()
{
privateFunction();
}
OsmanFunction: function()
{
OsmanFunction();
}
}})();
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>

You need formatting your code. Really.
var a = (
function () {
var privateFunction = function () {
alert('Hello');
};
var OsmanFunction = function () {
alert('Osman');
};
return {
publicFunction: function() {
privateFunction();
},
OsmanFunction: function() {
OsmanFunction();
}
};
})();
document.getElementById("hitme").addEventListener('click', a.OsmanFunction);
This is working version.
But... in your code:
return
{
You can't transfer return object to the next line.
You have no "," on return object between functions
{
publicFunction: function()
{
privateFunction();
}
OsmanFunction: function()
{
OsmanFunction();
}
}
a is not defined.
Please, in fature be attentive to your code, you make code for an other developers, who will support your project, not for machines.

Your function is returning undefined (returning nothing, which is undefined in js). The lines:
return
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
}
Is interpreted as:
return;
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
};
Therefore it is equivalent to:
return undefined;
{
publicFunction: function()
{
privateFunction();
},
OsmanFunction: function()
{
OsmanFunction();
}
};
Be very careful with line breaks in javascript. If possible use a coding convention that avoids this kind of mistake. There are several coding conventions that work. Google "Crockford convention" or "standard.js". Either convention work so choose one that you like.
Anyway. I'd suggest you don't start an open brace { in a new line if possible. Get used to starting a brace at the end of the line. It avoids this error.

I think it was just poor formatting, but this is I think what your trying to achieve.
function Test(){
var privateFunction = function(){
alert('Hello');
}
var OsmanFunction = function(){
alert('Osman');
}
return {
publicFunction: privateFunction //NB This is no longer private if you expose it
, OsmanFunction: OsmanFunction
}
};
var tester = Test();
var btn = document.getElementById('hitme');
btn.addEventListener('click', function(e){
e.preventDefault();
tester.OsmanFunction()
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>

Try following code, you missed comma between "publicFunction" and "OsmanFunction" when these returning:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script>
a = (
function() {
var privateFunction = function() {
alert('Hello');
}
var OsmanFunction = function() {
alert('Osman');
}
return {
publicFunction: function() {
privateFunction();
},
OsmanFunction: function() {
OsmanFunction();
}
}
})();
</script>
</head>
<body>
<p> Please hit me</p>
</body>
</html>

Related

Passing data to a javascript file after loading fails

I have the following in my html
<html>
<body>
<script type="text/javascript">
var hccid=98964571;
function add_chatinline(){
var nt=document.createElement("script");
nt.async=true;
nt.src="http://localhost/ll.js";
var ct=document.getElementsByTagName("script")[0];
ct.parentNode.insertBefore(nt,ct);
console.log("state is ", SORCHAT)//SORCHAT is not defined
}
add_chatinline();
</script>
</body>
</html>
On the ll.js i have
var SORCHAT = SORCHAT || (function () {
return {
init: function (Args) {
console.log("hash is ", Args)
},
};
}());
But now am getting an error of SORCHAT is not defined.
By adding window.onload that is
<script>
window.onload = function(){
SORCHAT.init(12736474676); //this works
}
</script>
But whenever i include another javascript file with window.onload function the SORCHAT.init is not executed.
What am i missing.
You are probably overwriting the window.onload when using it multiple times. You can prevent that with the help of the addEventListener-function.
window.onload = function () {
console.log('onload #1');
}
window.onload = function () { // This replaces the first onload (#1)
console.log('onload #2');
}
window.addEventListener('load', function () {
console.log('onload #A');
});
window.addEventListener('load', function () {
console.log('onload #B');
});

object delegation with module pattern

I'm trying to seperate concerns using the module pattern and everything is going Ok except that I'm trying to delegate the dom strings from a module (the UIController module) to another actually I succeeded at doing it once but I don't know what is happening know it didn't work
as you see above the Domstrings object is inside the UIcontroller module so I expose it to the public so the other modules could use it
and as you see I did it before and it works fine without any problem as you see below
but when I use it inside the internalController module I got this error
so here is where I'm using it in:
so here is my code and thank you in advance:
JS
var internalController = (function(UICtrl) {
addItem: function(day, from, to, text, goingToCkecked) {
var newPlan, ID,Dom=UICtrl.getDOMstrings();
if (day === 'pick the day') {
document.querySelector(Dom.errorCase).style.visibility = "visible";
document.querySelector(".optionList").classList.add("error-red");
} else {
document.querySelector(".error-case").style.visibility = "hidden";
document.querySelector(".optionList").classList.remove("error-red");
console.log("that is me");
}
document.querySelector("#optionList").addEventListener("change", function(e) {
document.querySelector(".error-case").style.visibility = "hidden";
document.querySelector(".optionList").classList.remove("error-red");
});
})(UIController);
var UIController = (function() {
var DOMstrings = {
inputDay: ".optionList",
inputTimeF: ".inputTime",
inputTimeT: ".inputTime2",
inputText: ".inputText",
goingToCkecked: ".checkboxx",
inputBtn: ".add__btn",
planContainer: ".container",
errorCase: ".error-case",
optionList: ".optionList",
};
return {
getInput: function() {
return {
inputDay: document.querySelector(DOMstrings.inputDay).value,
inputTimeF: document.querySelector(DOMstrings.inputTimeF).value,
inputTimeT: document.querySelector(DOMstrings.inputTimeT).value,
inputText: document.querySelector(DOMstrings.inputText).value,
goingToCkecked: document.querySelector(DOMstrings.goingToCkecked).checked,
};
},
getDOMstrings: function() {
return DOMstrings;
},
}
}
};
})();
var controller = (function(interCtrl, UICtrl) {
var input, newPlan;
function setupEventListeners() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddPlans);
document.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
ctrlAddPlans();
}
});
}
return {
init: function() {
console.log('the app has started');
setupEventListeners();
},
};
})(internalController, UIController);
controller.init();
// setInterval(function() {
// }, 100);
setTimeout(function() {
document.querySelector(".plansBackground").classList.add("height");
}, 1000);

JavaScript callback functions not executed

I just started learning about callback functions. Unfortunately I can't make this altered sample-code work.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$(".closebtn").click(function(){
function1(someVariable, function() {
function2(someOtherVariable);
});
});
function function1(param, callback) {
alert("Erste Funktion");
callback();
}
function function2(param) {
alert("Zweite Funktion");
}
})
</script>
When I click on the button nothing happens. Can anyone help?
Your example works for me. Let me know what you think:
// these need to be defined
var someVariable = 'example value';
var someOtherVariable = 'example value';
$(document).ready(function() {
$(".closebtn").click(function() {
function1(someVariable, function() {
function2(someOtherVariable);
});
});
function function1(param, callback) {
console.log("Erste Funktion");
callback();
}
function function2(param) {
console.log("Zweite Funktion");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="closebtn">Close</button>

JQuery plugin class not working

I am developing a JQuery plugin. I need to use OOP inside my plugin. However, the class not working as I expected. When I initiate a new instance of the class, it is only the first line of its code that is executing. What is wrong with this code and how to execute a constructor of this class on initiation?
(function ($) {
var FunClass;
FunClass = function () {
console.log("FunGlobal");
function FunClass() {
console.log("FunConstructor");
}
FunClass.prototype.letsFun = function () {
console.log("FunMethod");
}
}();
$.fn.fun = function () {
var funClass;
return this.each(function () {
funClass = new FunClass();
funClass.letsFun();
});
};
}(jQuery));
Here is the console output: Console Output
Thanks for help.
Seems you've forgot to return FunClass:
(function($) {
var FunClass;
FunClass = (function() {
console.log("FunGlobal");
function FunClass() {
console.log("FunConstructor");
}
FunClass.prototype.letsFun = function() {
console.log("FunMethod");
}
return FunClass; // you missed this line
})();
$.fn.fun = function() {
var funClass;
return this.each(function() {
funClass = new FunClass();
funClass.letsFun();
});
};
}(jQuery));
// Usage
$(function() {
$('body').fun();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JavaScript - Constructing global objects with nested functions

I'm quite new to JavaScript, and for the life of me I can't fugure out how to correctly construct a global object in my script:
var Global =
{
button1Handler: function () {
this.button1 = $("#button1");
this.init = function () {
this.button1.on("click", function () { alert("button1 clicked"); });
}
},
button2Handler: function () { /* ... */ },
init: function () {
this.button1Handler.init();
this.button2Handler.init();
}
};
$(function () {
Global.init();
});
This code produces the following error:
TypeError: this.button1Handler.init is not a function
If I change it to this.button1Handler().init(); the error goes away, but the Button1Handler.init() function never gets called.
How do I correct the code above?
I am not sure why you have to do like this. But if you really want to you can achieve what you want with this:
button1Handler: function () {
return {
button1: $("#button1"),
init: function () {
this.button1.on("click", function () { alert("button1 clicked"); });
}
};
},
and then you can call init as this.button1Handler().init().
In this case this.button1Handler() function returns an object which further has an init method.
You are getting error because this.button1Handler is a function and you will have to create an instance of it to access properties of it.
var Global = {
button1Handler: function() {
//this.button1 = $("#button1");
this.init = function() {
//this.button1.on("click", function () { alert("button1 clicked"); });
console.log("Button1 init")
}
},
button2Handler: function() {
this.init = function() {
console.log("Button2 init")
}
},
init: function() {
new this.button1Handler().init();
new this.button2Handler().init();
}
};
(function() {
Global.init();
})();
A better solution is to return necessary properties:
Sample
var Global = {
button1Handler: function() {
var button1 = $("#button1");
var init = function() {
button1.on("click", function() {
console.log("Button1 clicked")
});
}
return {
init: init
}
},
button2Handler: function() {
var button2 = $("#button2");
var init = function() {
button2.on("click", function() {
console.log("Button2 clicked")
});
}
return {
init: init
}
},
init: function() {
this.button1Handler().init();
this.button2Handler().init();
}
};
(function() {
Global.init();
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="button1">button 1</button>
<button id="button2">button 2</button>
In the following code, button1 is a private variable since it is not exposed using return statement, but init is public property. So you can have any number of properties, but only the properties that you return will be public properties.
button1Handler: function() {
var button1 = $("#button1");
var init = function() {
button1.on("click", function() {
console.log("Button1 clicked")
});
}
return {
init: init
}
}
It is because button1Handler does not return an executed function. In this.button1Handler().init() button1Handler function is invoking the init there this will point to the button1Handler() scope hence function init will be accessible.

Categories