I have observed that the reference of this
inside a function, added as an event listener, points to something else. Despite reading through an informative resource and checking stackoverflow, I am still unsure how to resolve this issue (as I am relatively new to the concepts of "oop" and the module pattern in javascript).
Below is the code snippet of my module:
var myModule = myModule || ( function() {
// Function for adding event listeners compatible with all browsers
function addEvent( element, event, listener ) {
if ( element.addEventListener ) {
return element.addEventListener( event, listener, false );
} else if ( element.attachElement ) {
return element.attachElement( "on" + event, listener );
}
}
return {
init: function() {
addEvent(
document.getElementById( "myElementId" ),
"click",
this.processMyElement
);
addEvent(
document.getElementById( "myOtherElementId" ),
"click",
this.processMyOtherElement
);
},
hideElementById: function( elementId ) {
document.getElementById( elementId ).style.display = "none";
},
showElementById: function( elementId ) {
document.getElementById( elementId ).style.display = "block";
},
processMyElement: function() {
this.hideElementById( "myElementId" );
this.showElementById( "myOtherElementId" );
},
processMyOtherElement: function() {
// Other functionality here...
}
};
}() );
The problem lies in this
not referring to the current object when calling hideElementById
within processMyElement
, but instead referencing the element with the eventListener.
I have tried several methods without success:
- removing the
return
statement inaddEvent
, - creating a private property 'that' inside the module before the definition of
addEvent
and using it inprocessMyElement
, - using
apply
method in theinit
function, which unfortunately callsprocessMyElement
immediately when adding the listener to the element.
Seeking guidance on how to tackle this challenge. I have attempted various approaches but none seem to provide a clear solution...
Note: I aim to create testable code, hence the inclusion of hideElementById
and showElementById
methods to separate functionalities (even though it might be slightly cumbersome at this stage...).