Passing Dynamic Data to Event Handlers - J Query

Problem
You want to pass certain values to an event handler, but they’re not known at “binding time,” and they would change with each call to the handler.

Solution

There are two ways of solving this problem:

  • Passing extra arguments to trigger()

  • Passing a custom event object to trigger()

Both approaches work, and neither is clearly better than the other. The second approach was a little awkward to use before jQuery 1.3. Since this version, it has become pretty straightforward and less problematic. I’ll explain each option in detail in the “Discussion” section.
Passing data to the handler, instead of making the function grab it from somewhere (global variables, jQuery namespace, etc.), makes the code easier to maintain because you keep handler functions simple and agnostic from the environment.
This also allows you to reuse the same handler for many situations.

Discussion

Passing extra arguments

trigger() can receive one or more values that will be passed on to the triggered handlers.
These values can be of any type and any amount. When you have more than one, you need to wrap them with an array:

The bound function for the preceding case would be something like this:

This approach is simple and easy to read. The problem is, it looks pretty bad when you need to receive many arguments; I personally would n’t go beyond four to five.
It’s also kind of misleading if the reader is used to the common function(e){ } kind of function.
You start to wonder, where do these other arguments come from ?
Used within a programmatic event:

Passing a custom event object

If you choose to pass a custom event object instead, each value you pass has to be accessed as an attribute on the event object received by the handler.This means that, no matter how many data you’re passing, the handler will always have only a single argument, the event object.
This is already an advantage over the first approach, because it makes the function declaration less verbose.
As mentioned, this approach is much nicer to use since jQuery 1.3. Here’s how you’d code the first example with a custom object:

Some more examples.Passing an object literal is actually a shortcut to creating an instance of jQuery.Event.‡ This is the alternative way:

You can, of course, use jQuery.extend instead of setting one attribute at a time.
You do need to create an event object yourself if you plan on retrieving data from this object after the call to trigger(). That’s, by the way, a cool technique to pass information from the handler to the caller (we’ll get into this in the next chapter).

What’s the difference with event.data?
Using event.data is useful for static values that are accessible at the time when the function was bound. When the data you need to pass must be evaluated later (or each time), event.data won’t do for you.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics