簡體   English   中英

JavaScript代碼在回調中無效

[英]JavaScript code not working within a callback

在以下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));
  }

嘗試在回調中捕獲范圍並使用它。

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));
  }
};

您的showDialog方法的submitCallback也需要綁定 - 它訪問this.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)
//    ^^^^^^^^^^
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM