我想写一个小的JavaScript库。
这很简单。这是一个小包装上传文件。
无论如何:我在事件中访问实例有一个问题。
我试着这样做:
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);
}
}
它给我的错误:。uploadFile不是一个函数
如果我这样做:
.....
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);
}
它的工作原理。但我的问题是:我需要事件处理程序。
获取发送者是没有问题的。元素/这个。dropDiv,…)
但是我如何获得事件与参数和FileUpload实例?
谢谢!
这似乎行得通。在初始代码this
中,函数dropHandler()
引用了drop元素。我将这两个函数更改为箭头语法。
另外(和IMHO更令人兴奋的)是如何新的箭头函数绑定,或实际上不绑定它自己的这个。箭头函数在词法上绑定了它们的上下文,所以这实际上指的是原始上下文。箭头函数与词法
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", 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>