The signature of the delegate $addHandler wants has one parameter, (which from my .NET upbringing is called "e") that acts as event args. This object contains a lot of information, such as a reference to the "sender" (again, from .NET, the control that fired the event), mouse location data, etc. This is passed for free; no additional works needs to be done if this is all you need.
However, if you want to pass additional parameters, you need to create a callback and use that as the third parameter send to $addHander. Using this technique, the above $addHandler call needs to be modified, as follows:
You can only pass one variable, so if your event handler needs additional parameters, stuff them into an Array first:
Here is the gotcha: since we are explicitly creating a callback method to be used as the delegate for the event handler, you'd assume we are forcing our event handler to match the signature of the callback. So attempting the following:
Will actually result in an error, and a very misleading error at that: "someVariable" will be undefined! When I first encountered this, I went down the path of making sure that I correctly declared and populated my array, correctly used "Function.createCallback" instead of something like "function.CreateCallback," etc. But nothing made sense.
The problem is that $addHandler will ALWAYS respect the "e" parameter and pass it along with the callback's argument. Therefore, the correct syntax for our event handler is:
If you are manually calling these event handlers, you then still need to supply the "e." I usually do something like:
The works well because if you don't need the "e" then chances are you are really using this event handler more like a normal method that also happens to listen to an event. And if you are using "e," you probably won't be calling this method outside the context of the event. (For example, if your event is mouse driven (like mousemove), and you need the coordinates of the cursor, then how could you fire this off manually anyways?)