Jump to content
Larry Ullman's Book Forums

Passign Arguments To Event Listener Functions


Recommended Posts

In Chapter 8, pages 167-169, the advantages of the four methods of adding an event listener to an object are discussed, with various pro and cons. One thing is not mentioned at all: how do you pass an argument to a function that is an event listener. Then around page 174, an example is given where an onload event listener is assigned an anonymous function which includes two function calls--one of them with an argument.

 

Question: are anonymously assigned functions the only way to allow passing an argument to an event listener? Is this discussed somewhere in the book where I missed it?

 

Thanks!

Link to comment
Share on other sites

LBPSlava, in short, yes, anonymous functions are the only way to send arguments to functions from event listeners.

The reason why is because only function references (not function calls) can be assigned to event listeners. However, you have to use a function call to send an argument to a function.

As a result, you have to use an anonymous function (which is a function reference and a function definition wrapped into one) in order to both assign a function reference to to the event listener but also allow you to define what is performed within the function (e.g., make a function call with arguments).

 

With that said, I typically don't assign anonymous functions to event listeners. Not that you can't do it, but there are some downsides. Instead, I generally use the "this" keyword to accomplish what I want without the use of other variables. Also, you can use global (or pseudo-global) variables to get what you want without the need to pass arguments to a function from an event listener.

 

(Sorry for the vague answer toward the end there, but I'm pressed on time at the moment.)

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...