Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Illegal invocation on addEventListener

I get an Uncaught TypeError: Illegal invocation for both versions of this attempt to put down an EventListener: (I get the error when the listener should be added, not when I click on the target)

ronan.addEventListener("click", alert, false);

addEventListener.apply(ronan, ["click", alert, false]);

ronan is a div element that is returned successfully by the console so I don't think that's the problem. Any ideas why I get this error? I read this thread and I couldn't figure it out from that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to wrap alert in a function. This will work:

ronan.addEventListener("click", function() { alert('Hi'); }, false);

Here's a fiddle for proof. Using alert alone doesn't work because when a listener is executed the value of this within that function is set to the object on which it is listening. For example, if you set a listener on ronan, within that listener this === ronan. This presents a problem for alert because that function expects this to be equal to window. You can work around this (no pun intended) by wrapping the function in another function or by binding it to whatever it expects this to be:

document.body.addEventListener('click', alert.bind(window), false);

Don't forget that in IE < 9 you need to use attachEvent rather than addEventListener.


A note on using apply/call with addEventListener

Your second attempt won't work because you're trying to apply your arguments to window.addEventListener, as opposed to HTMLElement.prototype.addEventListener, which is a different function altogether:

// This won't work
addEventListener.apply(ronan, ["click", alert.bind(window), false]);

// This will work
HTMLElement.prototype.addEventListener.apply(ronan, ['click', alert.bind(window), false]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...