JavaScript代码在回调中不起作用
在下面的JavaScript代码中,如果warnBeforeNew为false,则文件打开代码可以工作。但是,如果warnBeforeNew为true,则不会出现错误,而是给出一个错误“UncaughtTypeError:无法读取未定义的属性“root” 我不知道这是否与作用域有关,但如何让文件加载代码在回调中工作?谢谢JavaScript代码在回调中不起作用,javascript,Javascript,在下面的JavaScript代码中,如果warnBeforeNew为false,则文件打开代码可以工作。但是,如果warnBeforeNew为true,则不会出现错误,而是给出一个错误“UncaughtTypeError:无法读取未定义的属性“root” 我不知道这是否与作用域有关,但如何让文件加载代码在回调中工作?谢谢 Editor.prototype.open = function(path) { if (Editor.warnBeforeNew==true){ this.sho
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));
}
尝试捕捉回调之外的作用域并使用它
Editor.prototype.open = function(path) {
var that=this;
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;
that.filesystem.root.getFile(path, {}, that.load.bind(that), error.bind(null, "getFile " + path));
}
});
} else {
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}
};
submitCallback
到您的showDialog
方法也需要绑定-它访问这个失败的.filesystem.root….
this.showDialog({
…,
submitCallback: function() {
Editor.warnBeforeNew=false;
this.filesystem.root.getFile(path, {}, this.load.bind(this), error.bind(null, "getFile " + path));
}.bind(this)
// ^^^^^^^^^^
});
你忘了在bind中将
这个替换为东西你忘了将这个替换为那个其中加载方法是boundya你是对的那个.filesystem.root.getFile(路径,{},那个.load.bind(那个),error.bind(null,“getFile”+path))代码>