0

Mac OS X で Chrome 12 を使用しており、ドキュメント内に jQuery 1.6.1 を含めました。

次のコードでファイルを読み取ろうとすると、ファイルの読み取り中にエラーが発生するため、 this.error.onerror() が呼び出されますが、FileReader-Object this.reader はもう存在せず、できませんエラーを取得します。エラーが発生する理由もわかりません。これは、読みたい通常のテキストドキュメントです。

function FileHandler(files, action) {
    console.log('FileHandler called.');

    this.files = files;
    this.reader = new FileReader();
    this.action = action;

    this.handle = function() {
        console.log('FileHandler.handle called.');

        for (var i = 0; i < this.files.length; i++) {
            this.reader.readAsDataURL(files[i]);
        }
    }

    this.upload = function() {
        console.log('FileHandler.upload called.');
        console.log(this.reader);

        data = {
            content: this.reader.result
        }

        console.log(data);
    }

    this.error = function() {
        console.log('An error occurred while reading a file.');
        console.log(this.reader.error);
    }

    this.reader.onload = this.upload;
    this.reader.onerror = this.error;
}

このコードは、次のコンソール出力を作成します: http://cl.ly/0j1m3j0o3s071Y1K3A25

4

2 に答える 2

0

内部.onerrorは、this新しい関数 (新しいスコープを持つ) であるため、外部と同じではありません。

this次のように静的に設定して追跡します。

var _this = this; // _this won't change
this.reader.onerror = function() {
    console.log('An error occurred while reading a file.');
    console.log(_this.reader.error);
}
于 2011-06-20T20:11:40.863 に答える