I am facing an issue with the following code snippet :
<!DOCTYPE html>
<html>
<head>
<title>Drag-Drop tests</title>
<meta charset="UTF-8">
</head>
<body>
<script>
var body = document.body;
var cursor = document.createElement("div");
cursor.innerText = "Content of files :\n";
cursor.ondragover = e => e.preventDefault();
cursor.ondrop = function(e) {
e.preventDefault();
if (e.dataTransfer.items) {
for (var i = 0; i < e.dataTransfer.items.length; i++) {
if (e.dataTransfer.items[i].kind === "file") {
var file = e.dataTransfer.items[i].getAsFile();
file.cursor = document.createElement("p");
body.appendChild(file.cursor);
file.cursor.innerText = file.name + " contains :";
file.text().then(function(value) {
file.cursor.innerText += " " + value;
});
}
}
}
else {
for(var i = 0; i < e.dataTransfer.files.length; i++) {
var file = e.dataTransfer.files[i];
file.cursor = document.createElement("p");
body.appendChild(file.cursor);
file.cursor.innerText = file.name + " contains :";
file.text().then(function(value) {
file.cursor.innerText += " " + value;
});
}
}
};
body.appendChild(cursor);
</script>
</body>
</html>
Upon dropping two files on the div element, the output I receive is as follows :
Content of files :
File1.txt contains :
File2.txt contains : Content of file 1 Content of file 2
In the 'file.text().then' function, "file" refers to the last file reference declared.
If I replace file.cursor.innerText += with this.cursor.innerText += I get the following output :
Content of files :
Content of file 1 Content of file 2
File1.txt contains :
File2.txt contains :
In the 'file.text().then' function, "this" points to the first caller which is the div itself.
Is there a way to achieve this output :
Content of files :
File1.txt contains : Content of file 1
File2.txt contains : Content of file 2
While keeping anonymous nested functions as parameters for callers.
I understand that the 'then' does not execute at the time it's defined. Can I attach data to an object and retrieve it during callback execution?
Thank you in advance.