2

AJAX 呼び出しからの辞書の単語のリストを、JavaScript で定義した Dictionary オブジェクトに入れようとしています。次のように、Google Closure Toolkit を使用して呼び出しを行います。

frankenstein.app.Dictionary = function(dictionaryUrl) {
  /** @private */ this._words = new goog.structs.Set();
  log("sending request");
  goog.net.XhrIo.send(dictionaryUrl, this.initDictionary);
}

frankenstein.app.Dictionary.prototype.initDictionary = function(e) {
    var xhr = e.target;
    this._words.addAll(xhr.getResponseText().split('\n'));
    log('Received dictionary file with ' + this._words.size());
}

initDictionary メソッド内では、残念ながら、「this」は Dictionary オブジェクトではなく goog.net.XhrIo を参照しています。initDictionary で this として参照される Dictionary オブジェクトを取得する方法はありますか? または、変数を設定する他の方法はありますか?ありがとう!

4

1 に答える 1

1

コールバックは、次のようfrankenstein.app.Dictionary.prototype.initDictionaryに のインスタンスにバインドできます。frankenstein.app.Dictionary

/** @constructor */
frankenstein.app.Dictionary = function(dictionaryUrl) {
  /** @private */ this._words = new goog.structs.Set();
  log("sending request");

  var xhr = new goog.net.XhrIo();
  goog.events.listenOnce(xhr, goog.net.EventType.COMPLETE, this.initDictionary,
      false /* capture phase */, this);
  xhr.send(dictionaryUrl);
};

frankenstein.app.Dictionary.prototype.initDictionary = function(e) {
  var xhr = /** @type {goog.net.XhrIo} */ (e.target);
  this._words.addAll(xhr.getResponseText().split('\n'));
  log('Received dictionary file with ' + this._words.size());
  xhr.dispose(); // Dispose of the XHR if it is not going to be reused.
};

goog.events.listenOnce(または代わりに)の 5 番目の引数goog.events.listenは、リスナーが呼び出されるスコープ内のオプションのオブジェクトです。

于 2012-07-22T00:00:23.873 に答える