I am showing an example of an object constructor below. Suppose one of its methods (“method1”) creates a SPAN node inserted into the HMTL document. The span node will be clicked by the mouse, so an event listener is added. The handler too is a method of the constructed object.
[CODE]function objConstructor(arg) {
this.method1 = function () = {
node = document.createElement(“span”);
node.addEventListener(“click”, function() { this.showElem(true); }, false);
// more code to put text in span, then append note to parent in HTML
};
this.showElem = function(showState) {
if (showState == true)
// code to show the element
else
// code to hide the element
};
}
The problem is in the 2nd argument of the addEventListener() method, since the scope of the handler call is outside the constructor and a function-not-defined error will be reported.
I am thinking some kind of closure should be defined such that the handler is made a method of the object. The code is proving a challenge however.