我正在尝试将来自 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/