0

在以下 JavaScript 代码中,如果 warnBeforeNew 为 false,则文件打开代码有效。但是,如果 warnBeforeNew 为真,则不会,而是给出错误“未捕获的类型错误:无法读取未定义的属性 '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));
  }
};
4

3 回答 3

2

您必须保存的值,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));
  }
于 2013-08-18T12:52:36.303 回答
0
于 2013-08-18T13:00:00.337 回答
0

Try to catch the scope out side the callback and use it.

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));
  }
};
于 2013-08-18T12:56:40.877 回答