Assuming there are many popups (like more than 30) in my page, and I need to make them listen to a click event handler. Below is Example 1 in the jQuery syntax:
$('.popup').on('click', function () {
// do something
});
I have learned a suggestion in the past that the Example 1 approach is bad for performance/memory (I can't recall the exact reason) because each element listens to an independent anonymous function. And the suggestion said that it is better to name the event handler and then make all the elements listen to the named event handler, like the following Example 2:
function clickEventHandler() {
// do something
}
$('.popup').on('click', clickEventHandler);
Now, for each popup, I need to pass a variable which is specific to the popup, into the named event handler. The approach I think of is using the .bind()
mehtod like the following Example 3:
function clickEventHandler(someInfo) {
// do something
}
$('.popup').each(function () {
$(this).on('click', clickEventHandler.bind(null, $(this).attr('data-some-info')));
});
However, it concerns me that the description of the .bind()
method says:
The
bind()
method creates a new function...
My question is: What does "creates a new function" mean exactly? Does it mean creating an independent anonymous function every time the method is used and is as bad as Example 1 when it comes to performance/memory?
Approach 1 is just fine - you're only creating a single function, and passing it to every event handler.
Now, if you had something like
$('.popup').each(function() {
$(this).on('click', function () {
// do something
});
});
that would indeed be very slightly wasteful, because you'd be creating a new callback function for every iteration in the loop.
But
Assuming there are many popups (like more than 30) in my page
30 is absolutely nothing with modern hardware. Now, if you had a thousand, or ten thousand, then there might be something to consider, maybe.
My question is: What does "creates a new function" mean exactly? Does it mean creating an independent anonymous function every time the method is used and is as bad as Example 1 when it comes to performance/memory?
Example 1 is just fine - but calling .bind
in a loop is somewhat similar to my snippet above, in which there are many separate functions in memory.
To achieve what you want:
function handleClick(e) {
const someInfo = this.dataset.someInfo;
// rest of function
}
$(document.body).on('click', '.popup', handleClick);