我正在尝试将一个来自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中将Dictionary对象引用为this?或者其他一些设置变量的方法?谢谢!
答案 0 :(得分: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
)是一个可选对象,其范围将调用侦听器。