javascript - 使用 XhrIo 填充 Object 的变量

标签 javascript google-closure-library

我正在尝试将来自 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 对象。有没有办法让 Dictionary 对象在 initDictionary 中被引用为 this?或者其他一些设置变量的方法?谢谢!

最佳答案

回调 frankenstein.app.Dictionary.prototype.initDictionary 可以绑定(bind)到 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)的第五个参数是一个可选对象,在其范围内将调用监听器。

关于javascript - 使用 XhrIo 填充 Object 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596640/

相关文章:

javascript - 单击更改 anchor 标记的内容和目标

javascript - 使用正则表达式反转字符串中的元音

javascript - 在正则表达式中使用 '|' 运算符时确定匹配的子模式

javascript - Javascript/google 闭包库中的类型转换

javascript - 如何将 HTML5 Web Workers 与 Google Closure Tools 结合使用?

javascript - Dojo:TypeError:marketStore.query 不是函数

javascript - 为什么日期格式没有给出正确的值?

javascript - 闭包库 ondevicemotion 从未触发

touch - 移动触摸支持——在 Closure-library 中

localization - 如何在 Google Closure 中进行本地化