I would like a write a small JavaScript Library.
It is very simple. It is a small Wrapper to Upload Files.
Anyway: I have a problem to access the Instance with in the Event.
I try it like this:
class FileUpload
{
constructor(element)
{
this.element = element;
this.dropDiv = document.createElement("div");
this.dropDiv.style = "border: 2px solid #007bff; background-color: lightblue; width: 100%;border-radius: 25px;";
this.dropDiv.className = "text-center";
this.dropDiv.innerHTML = "Upload<br>File<br>Here";
this.dropDiv.addEventListener("dragover", function(event)
{
event.preventDefault();
});
this.dropDiv.addEventListener("drop", this.dropHandler);
this.element.appendChild(this.dropDiv);
}
dropHandler(event)
{
event.preventDefault();
this.uploadFile("Test");
}
uploadFile(file)
{
console.log("Logic to Upload the file or whatever...");
console.log(file);
}
}
It gets me the error: this.uploadFile is not a function
If i try it like this:
.....
this.dropDiv.addEventListener("drop", this.dropHandler('Test'));
this.element.appendChild(this.dropDiv);
}
dropHandler(testVar)
{
console.log(testVar);
console.log(this);
this.uploadFile("Test");
}
uploadFile(file)
{
console.log("Logic to Upload the file or whatever...");
console.log(file);
}
It works. But my problem: i need the eventhandler.
Getting the sender is no problem (this.element / this.dropDiv, ...)
But how do i get the event with the parameters AND the FileUpload instance?
Thank you!
This seams to work. In the initial code this in the function dropHandler() refereed to the drop element. I changed the two functions to arrow syntax.
In addition(and IMHO more exciting) is how the new Arrow Function binds, or actually DOES NOT bind it’s own this. Arrow Functions lexically bind their context so this actually refers to the originating context. Arrow Functions and Lexical
this
So, the function will bind to the object, not the element.
class FileUpload {
constructor(element) {
this.element = element;
this.dropDiv = document.createElement("div");
this.dropDiv.style = "border: 2px solid #007bff; background-color: lightblue; width: 100%;border-radius: 25px;";
this.dropDiv.className = "text-center";
this.dropDiv.innerHTML = "Upload<br>File<br>Here";
this.dropDiv.addEventListener("dragover", e => e.preventDefault());
this.dropDiv.addEventListener("drop", this.dropHandler);
this.element.appendChild(this.dropDiv);
}
dropHandler = e => {
e.preventDefault();
this.uploadFile("Test");
}
uploadFile = file => {
console.log("Logic to Upload the file or whatever...");
console.log(file);
}
}
var f1 = new FileUpload(document.querySelector('div'));
<div>test</div>