在以下 JavaScript 代码中,如果 warnBeforeNew 为 false,则文件打开代码有效。但是,如果 warnBeforeNew 为 true,则不会,而是给出错误“Uncaught TypeError:无法读取未定义的属性“root””。
我不知道这是否与范围有关,但是如何让文件加载代码在回调中工作?谢谢。
Editor.prototype.open = function(path) {
if (Editor.warnBeforeNew==true){
this.showDialog({
dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
submitLabel: 'Discard',
cancelLabel: 'Cancel',
submitCallback: function() {
Editor.warnBeforeNew=false;
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
};
最佳答案
您必须保存 this
的值,因为调用回调时,它使用与外部函数不同的接收器:
if (Editor.warnBeforeNew==true){
var thing = this; // choose a more meaningful name if possible...
this.showDialog({
dialogLabel: 'You have unsaved changes. Are you sure you want to discard them and open a different file?',
submitLabel: 'Discard',
cancelLabel: 'Cancel',
submitCallback: function() {
Editor.warnBeforeNew=false;
thing.filesystem.root.getFile(path, {}, thing.load.bind(thing), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
关于JavaScript 代码在回调中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299254/