Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onload without global variable

Tags:

javascript

I'm trying to use windows.load without global variable.

The HTML code:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Test</title>
    <link rel="stylesheet" href="main.css">
    <script type="text/javascript" src="script.js"></script>
</head>
<body>

<form>
    Name: <input type="text" id="txt1"><br><br>
    <input type="button" value="Check Input" id="b1">
</form>

</body>
</html>

The JavaScript global variable code:

/*jslint browser: true*/

var myButton;

window.onload = function () {
    "use strict";
    myButton = document.getElementById("b1");
    myButton.addEventListener("click",alertMM);
};

function alertMM() {
    "use strict";
    window.console.log(myButton.value);
}

And finally the NOT WORKING without global variable code:

/*jslint browser: true*/

var myNS = {
    myButton: undefined,
    //
    setUp: function () {
        "use strict";
        myNS.myButton = document.getElementById("b1");
        myNS.myButton.addEventListener("click", alertMM);
    }
};

window.onload = myNS.setUp();

function alertMM() {
    "use strict";
    window.console.log(myNS.myButton.value);
}

The reason that I want to stop using global variable is that I'm afraid it will conflict with future code.

Thanks in advance

Adrian

like image 258
Adrian Gherasim Avatar asked Apr 18 '15 13:04

Adrian Gherasim


1 Answers

In:

window.onload = myNS.setUp();

when you define the window.onload callback, you should assign it the function itself (just myNS.setUp) so it can be called later. What your code doing instead is calling the function immediately and assigning the result.

like image 161
Touffy Avatar answered Sep 30 '22 07:09

Touffy