Reusing a Handler Function with Different Data - J Query

Problem
You’ve come into a situation where you have many bindings, and the handler functions look pretty similar. It does n’t matter whether these bindings are applied to different element/event combinations. The thing is, you don’t want to repeat yourself over andover (who does?). Here’s an example:

As you can see, the only differences noticed on each handler are the color and the panel to show. The amount of code would grow as you add more buttons or each time the handler functions get larger.

Solution

bind() accepts an optional data argument to be bound together with each specific handler function. The data values will be accessible from within this function by accessingevent.data† where event is the event object argument provided by jQuery.
Note that this value can be anything...an array, a string, a number, or an object literal.
It’s a common approach to pass an object literal, even if you are just passing one value,to make the code more readable. This way, the name you give this single attribute within the object will make your code a little more self-explanatory.

Discussion

event.data is used to provide pre computed values to a function, which means the values you will be passing to bind() need to be already available at binding time. To handle more “dynamic” values, there’s another way that we’ll learn about in Recipe (Passing Dynamic Data to Event Handlers).
The solution to the previous problem could look something like this:

Of course, you could make this even shorter by using a loop. This approach is called amacro by some coders, and it’s a very common approach for jQuery code.
These macros will surely reduce the code length and can sometimes improve codereadability. Some other times, they’ll just make your code completely unreadable, souse them with caution.
Here’s how you could do it:

As you can see, I haven’t used the data argument because we don’t really need it. The code is now somewhat shorter, but not that much, and it’s not more readable.
The conclusion is that both approaches can be used on this kind of situation. Depending on the problem, one could be better (shorter, more readable, easier to maintain)than the other.


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

J Query Topics