Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
LBPSlava

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!

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...