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
579 views
in Technique[技术] by (71.8m points)

asynchronous - Javascript, addEventListener callback function executes immediately and only once?

I've noticed a difference between function and function() for addEventListener's callback. Which isn't a problem till I tried passing a parameter. Basically,

element.addEventListener("hover", logInput, false );
function logInput(){
    console.log('registered!');
}

works as intended, but adding parenthesis will cause it log immediately, without continual response to the event trigger:

element.addEventListener("hover", logInput(), false );
function logInput(){
    console.log('registered!');
}

Why is this? And how can I get it to work while passing a parameter such as:

element.addEventListener("hover", logOnInput(this), false );
function logOnInput(triggeredElement){
    console.log(triggeredElement);
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Its a javascript when you want to call a function you use parentheses. Without parentheses outside a function is useless. But inside a function as argument you use the function without the parentheses so that when that event occurs then only it would run. If you call a function using parentheses inside function argument it will be executed immediately and would also run when the event occurs. To call a function with its parameters inside a function and just to invoke in that event you need to use the bind method like below:

element.addEventListener("hover", logOnInput.bind(null, argument1, argument2, etc), false );

However, if you want to select the context as this then I would recommend you to use like this:

function logOnInput(elem,arguments) {
  //now you can use **elem** to refer **this**
}

And use the anonymous function for the hover event like this:

element.addEventListener("hover", function(){
   logOnInput(this,arguments)
}, false );

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

...