Reputation: 403
What is a better way to write this code, i feel like i should be able to reference the target in a less hard coded way. is it ok to add the actual object to the variable instead, and if so, how do i test/verify where the event is added?
var o="window"; // or "document" or "body" or maybe some at the moment unknown elements id
if(o=="window"){
window.addEventListener();
}
else if(o=="document"){
window.document.addEventListener();
}
else if(o=="body"){
window.document.body.addEventListener();
}
Upvotes: 1
Views: 54
Reputation: 22265
you can do that
const elementX =
{ 'window' : window
, 'document' : window.document
, 'body' : window.document.body
}
var o="window";
elementX[o].addEventListener( ... );
Upvotes: 2
Reputation: 1527
I think you should add the object to the variable instead. That way your code just looks like this:
function addEventHandler(dom_object) {
if (dom_object) domobject.addEventListener("click", function(e) {
var target = (e || window.event).target
switch (target) {
case: window:
case: document:
case: document.body:
//....
}
});
}
addEventHandler(window)
addEventHandler(document)
addEventHandler(document.body)
I am not sure I understood you last question but you can check the object that triggered the event with event.target. See above code.
Upvotes: -1