使用打字稿和 'this' 对象读取本地文件
Reading a local file with typescript, and the 'this' object
我正在编写 TypeScript 浏览器应用程序。我需要读取 XML 文件的内容,并将其存储在 class 中。我对 'this' 对象有疑问。这是我目前所拥有的:
class FileTools {
text: string;
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
reader.onload = file => {
var contents: any = file.target;
this.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
start() {
document.getElementById("file-input").addEventListener("change", this.readSingleFile, false);
}
}
window.onload = () => {
var tcx = new FileTools();
tcx.start();
};
HTML有个文件选择框
输入类型="file" id="file-input"
问题是加载文件时,使用 'this' 指向文件 reader,而不是我的 class。如果我像这样先添加一个 'self' 变量:
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
var self = this;
reader.onload = file => {
var contents: any = file.target;
self.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
然后 self 指向输入框(因为这是外部方法的上下文)。
所以问题是,如何获取 FileTools 引用的真实 'this' 对象。
谢谢。
在 ES6 和 TypeScript 中,即使对于 class 方法,常规函数规则仍然适用。
在 start 方法中,您发送对 readSingleFile 函数的引用作为更改 event.That 函数的回调稍后将在输入字段的上下文中调用,从而更改 this 指向的内容。
尝试使用箭头函数来保留相同的上下文。
start() {
document.getElementById("file-input").addEventListener("change", e => {
this.readSingleFile(e); // this should now be FileTools
}, false);
}
我正在编写 TypeScript 浏览器应用程序。我需要读取 XML 文件的内容,并将其存储在 class 中。我对 'this' 对象有疑问。这是我目前所拥有的:
class FileTools {
text: string;
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
reader.onload = file => {
var contents: any = file.target;
this.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
start() {
document.getElementById("file-input").addEventListener("change", this.readSingleFile, false);
}
}
window.onload = () => {
var tcx = new FileTools();
tcx.start();
};
HTML有个文件选择框 输入类型="file" id="file-input"
问题是加载文件时,使用 'this' 指向文件 reader,而不是我的 class。如果我像这样先添加一个 'self' 变量:
readSingleFile(e) {
var fileName = e.target.files[0];
if (!fileName) {
return;
}
var reader = new FileReader();
var self = this;
reader.onload = file => {
var contents: any = file.target;
self.text = contents.result; <== Issue here. 'this' is the filereader
};
reader.readAsText(fileName);
}
然后 self 指向输入框(因为这是外部方法的上下文)。
所以问题是,如何获取 FileTools 引用的真实 'this' 对象。
谢谢。
在 ES6 和 TypeScript 中,即使对于 class 方法,常规函数规则仍然适用。
在 start 方法中,您发送对 readSingleFile 函数的引用作为更改 event.That 函数的回调稍后将在输入字段的上下文中调用,从而更改 this 指向的内容。
尝试使用箭头函数来保留相同的上下文。
start() {
document.getElementById("file-input").addEventListener("change", e => {
this.readSingleFile(e); // this should now be FileTools
}, false);
}