I thought that arrow function is "just" a shortcut for antonymous functions, so I've been using it quite a lot. However, recently I came across an example that arrow function caused some issues. Here's a sample code:
function refreshTable() {
$.ajax({
url: root + `/posts?userId=${userId}`,
method: 'GET'
}).then(function(data) {
for (var item of data) {
$('table.list tbody').append(`
<tr>
<td>${item.id}</td>
<td>${item.title}</td>
<td>${item.date}</td>
<td>
<a href="" data-id="${item.id}" class="getDetails">View</a> |
<a href="" data-id="${item.id}" class="getDetails">Delete</a>
</td>
</tr>
`);
}
$('.getDetails').click((e) => {
// $(this) is actually the ajax call, I can't access the "data" part
});
});
}
However, this works:
function refreshTable() {
$.ajax({
url: root + `/posts?userId=${userId}`,
method: 'GET'
}).then(function(data) {
for (var item of data) {
$('table.list tbody').append(`
<tr>
<td>${item.id}</td>
<td>${item.title}</td>
<td>${item.date}</td>
<td>
<a href="" data-id="${item.id}" class="getDetails">View</a> |
<a href="" data-id="${item.id}" class="getDetails">Delete</a>
</td>
</tr>
`);
}
$('.getDetails').click(function(e) {
// $(this) is the HTML element, so I can access "data"
});
});
}
Obviously, there is some logic to arrow functions, it creates a different scope for this
. So, what's going on? Could I achieve the same thing with an arrow function (to access HTML) or is that not possible in this case?
Thanks!