Here is the jsfiddle to illustrate the problem.
http://jsfiddle.net/mabqc2zs/4/
(same code below):
JavaScript
var namespace = namespace || {};
namespace.ExampleClass = function () {
this.eventAdded = false;
this.secondValue = null;
this.doSomething = function() {
var secondValue = this.secondValue;
};
this.event = {
eventAddedParam: this.eventAdded,
addListener: function(el, type, eAP2) {
if (!this.eventAddedParam) { // Ensures addEventListener registers only once.
var eAP = this.eventAddedParam;
el.addEventListener(type, function() { // Unable to add arguments to anonymous function
console.log("eAP2 value: " + eAP2); // false
console.log("eAP value: " + eAP); // true
try {
console.log("eventAddedParam value: " + eventAddedParam);
}
catch(e) {
console.log("Error: eventAddedParam variable is undefined");
}
});
eAP = true;
this.eventAddedParam = true;
}
}
};
};
var inst = new namespace.ExampleClass();
inst.event.addListener(document.getElementById("id1"), "focus", inst.eventAdded);
inst.event.addListener(document.getElementById("id1"), "focus", inst.eventAdded);
HTML
<input id="id1" type="text" />
I'm integrating addEventListener
to some Object Oriented JavaScript code.
I wanted to add arguments to the anonymous function, i.e. el.addEventListener(type, function()...
What I want to do is ensure addEventListener
gets registered once. Hence, in the code, I check if this.eventAddedParam
is true. It does work. Here is the problem. this.eventAddedParam
refers to eventAddedParam
, which is a literal object of this.event
. When I set eventAddedParam
to true, eventAdded
, which is a public variable of the ExampleClass
, is still set to false. This does does me no good.
Ultimately, what I want to do is change the value of eventAdded
to true within the addListener
function. I have not been able to figure this out.
And to further that, if possible, I'd like to make eventAdded
a private variable, yet access it within the addListener
function, but I have been able to figure that out, either.
Any help would be appreciated.
Update
I have an updated jsfiddle, after making the necessary changes.
http://jsfiddle.net/mabqc2zs/8/
For some reason, my IE 11 Developer Toolbar was not registering local variables. But it does work.