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”指的是 goog.net.XhrIo 而不是 Dictionary 对象。有没有一种方法可以让我在 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(或者, )的第五个参数goog.events.listen是一个可选对象,监听器将在其范围内被调用。

于 2012-07-22T00:00:23.873 回答