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

javascript - What's the difference between event handlers & listener?

What is the difference between event handlers and event listeners in JavaScript? They both execute a function when the event appears. I don't really get when to use event handlers and when to use event listeners.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A handler and a listener are one in the same - just synonyms for the function that will handle an event. "Handler" is probably the more accepted term, and is certainly more semantically correct to me. The term "listener" is derived from the code used to add an event to an element:

element.addEventListener('click', function() { /* do stuff here*/ }, false);

You could, however, get really nitpicky and break the two down into separate meanings. If you're so inclined, "handler" could be the term for the function that is going to handle an event when you add a "listener", thus one can have several "listeners" that utilize a single "handler". Consider:

// handler is synonymous with function 
function someFunction(e) {
  if (typeof e == 'undefined')
   alert('called as a function');
  else
   alert('called as a handler');
}


// use someFunction as a handler for a 
// click event on element1 -- add a "listener"
element.addEventListener('click', someFunction, false);
// use an anonymous function as a handler for a 
// click event on element1 -- add another "listener"
element.addEventListener('click', function () { alert('anonymoose'); }, false);


// use someFunction as a handler for a 
// click event on element2 -- add a "listener"
element2.addEventListener('click', someFunction, false);

// call someFunction right now
someFunction();

So in the above code, I have 2 "handlers" (someFunction and an anonymous function) and 3 "listeners".

Again, this is all semantics - for all practical purposes the terms listener and handler are used interchangeably. If a distinction need be made then a listener is a subscription to an event that will trigger a call to a handler (which is a function).

Clear as mud?


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

...