Reputation: 415
I'm trying to wrap my head around why this code isn't working. I read up on the DOM and adding event listeners, and I understand that an event listener can only be added to an object of the DOM. Technically the returned value of the _get_elem should be a DOM object and yet it still doesn't work. If anyone has any idea of why this doesn't work or point me in the direction of a resource that can explain how to do it, it would be greatly appreciated.
window.onload = funtion()
{
// works
document.getElementByID('element_id').addEventListener('click', _fn(), false);
var exfnvar = new exfn();
// doesn't work
exfnvar.exel.addEventListener('click', _fn(), false);
// also doesn't work
exfnvar._get_elem().addEventListener('click', _fn(), false);
};
var exfn = function()
{
this.exel = document.getElementByID('element_id');
this._get_elem = function()
{
return document.getElementByID('element_id');
}
};
function _fn()
{
// do something.
};
Upvotes: 0
Views: 301
Reputation: 1001
It worked fine for me after a few changes. One thing to note is capitalization:
getElementById
vs
getElementByID
Also, when you're passing a function as a callback, you don't want to include the parentheses. You only want to include that when you are executing the function.
Upvotes: 0
Reputation: 36965
If you write .addEventListener('click', _fn(), fale)
the _fn
is being executed in this very line and the result (return value) is being added as the event callback.
You have omitted the function body of _fn
, but assuming it doesn't return another function you should have used .addEventListener('click', _fn, false)
- this way a reference to _fn
is added as a listener, not the result of its execution.
Upvotes: 1
Reputation: 4896
You are calling the function and giving the return value as the callback to the event listener. instead you have to give the function as the callback.
change
document.getElementByID('element_id').addEventListener('click', _fn(), false);
to
document.getElementByID('element_id').addEventListener('click', _fn, false);
Same with other listners..
Upvotes: 4