How to make early binding for an event handler in JavaScript? (jQuery example)

JavaScript binding completion is excellent. But how do I bind early when I want?

I use jQuery to add links with event handlers in a loop in a div. The variable "aTag" changes in the loop. When I click links later, all links warn the same message, which is the last value of "aTag". How to link another alert message to all links?

All links should report with the value that 'aTag' had when the event handler was added, and not when it was clicked.

for (aTag in tagList) { if (tagList.hasOwnProperty(aTag)) { nextTag = $('<a href="#"></a>'); nextTag.text(aTag); nextTag.click(function() { alert(aTag); }); $('#mydiv').append(nextTag); $('#mydiv').append(' '); } } 
+4
source share
3 answers

You can pass data to the bind method:

 nextTag.bind('click', {aTag: aTag}, function(event) { alert(event.data.aTag); }); 

This will make a copy of aTag , so each event handler will have different values ​​for it. Your use case is the reason this parameter has a bind value.

Full code:

 for (aTag in tagList) { if (tagList.hasOwnProperty(aTag)) { nextTag = $('<a href="#"></a>'); nextTag.text(aTag); nextTag.bind('click', {aTag: aTag}, function(event) { alert(event.data.aTag); }); $('#mydiv').append(nextTag); $('#mydiv').append(' '); } } 
+3
source

You can also create a wrapper function that takes text as a parameter as a parameter and returns an event handler

 function makeAlertHandler(txt) { return function() { alert(txt); } } 

and replace

 nextTag.click(function() { alert(aTag); }); 

from

 nextTag.click(makeAlertHandler(aTag)); 
+1
source

You need to save a copy of this variable, for example:

 for (aTag in tagList) { if (tagList.hasOwnProperty(aTag)) { nextTag = $('<a href="#"></a>'); nextTag.text(aTag); var laTag = aTag; nextTag.click(function() { alert(laTag); }); $('#mydiv').append(nextTag); $('#mydiv').append(' '); } } 

The aTag variable changes every time you execute a loop, at the end of the loop it remains as the last element in the loop. However, each of the functions you create points to this same variable. Instead, you need the per variable, so make a local copy like mine above.

You can also shorten this with chaining, but I feel that in this case it is cloudy because the problem is with reach and links.

-1
source

Source: https://habr.com/ru/post/1307286/


All Articles