I seem to be having scope issues with using addEventListener inside of an immediate anonymous function.
Inside of the event listener, I am creating an instance of a Javascript “class” that is constructed outside of the immediate function (using a constructor and prototype).
In trying to keep with good practices, I wanted to use the immediate function to avoid global variables, and addEventListener to avoid using inline Javascript (thus separating it from html).
So how can I correctly do this without having scope issues, and what are good practices for doing so?
Here is my html:
<html>
<head>
<title>asdf</title>
</head>
<body>
<input type = "text" id = "userInput" />
<input type = "button" id = "submitButton" value = "submit" />
<script type = "text/javascript" src = "asdf.js" />
</body>
</html>
…and here is my Javascript asdf.js (which is not working):
// constructor for object-oriented processing of the user input
function Statement(expression)
{
this.expression = expression;
}
// instance method
Statement.prototype.checkSyntax = function()
{
var newExp = this.expression;
return newExp;
};
// immediate anonymous function
(function()
{
var submitButton = document.getElementById("submitButton");
// event listener for the submit button
submitButton.addEventListener("onclick", function(event)
{
var userInput = document.getElementById("userInput");
// creating a new object with constructor above
var expr = new Statement(userInput);
// calling instance method of the "class" Statement
alert(expr.checkSyntax() );
// disable the button after first use
event.stopImmediatePropagation();
}, false);
})(); // end of immediate anonymous function
addEventListenertakes an argument likeclick, notonclick. However, older IE’sattachEventrequiresonclick. Everything else seems fine.