【发布时间】:2014-07-30 03:07:28
【问题描述】:
所以,我有一个对象Async,它为(在这种情况下)来自 github 的 JSON 对象创建请求。
有一个方法 Async.createList 可以从 github JSON 对象创建一个特定属性的所有实例的列表。当Async.createList 被调用一次时它工作得很好,但我希望能够从同一个请求的不同目标属性创建多个列表,这就是它失败的地方。
理想情况下,列表将附加到Async.lists 对象,以便它们可以在Async 对象之外使用。现在,当我多次调用Async.createList 时,只有最后一个调用附加到Async.lists。
function Async(address) {
this.req = new XMLHttpRequest();
this.address = address
}
Async.prototype = {
lists : {},
create : function(callback) {
var self = this;
this.req.open('GET', this.address, true);
this.req.onreadystatechange = function(e) {
if (this.readyState == 4) {
if (this.status == 200) {
dump(this.responseText);
if (callback != null) callback()
} else {
dump("COULD NOT LOAD \n");
}
}
}
this.req.send(null);
},
response : function(json) {
return json == true ? JSON.parse(this.req.responseText) : this.req.responseText
},
createList : function(target) {
var self = this
var bits = []
this.req.onload = function(){
var list = self.response(true)
for(obj in list){
bits.push(self.response(true)[obj][target])
}
self.lists[target] = bits
}
},
}
我正在创建对象并像这样调用方法:
var github = new Async("https://api.github.com/users/john/repos")
github.create();
github.createList("name");
github.createList("id");
然后尝试:
github.lists
【问题讨论】:
标签: javascript json oop xmlhttprequest prototype