So, I have an object Async
that creates a request for (in this case) a JSON object from github.
There is a method Async.createList
that creates a list of all instances of a specific attribute from the github JSON object. It works just fine when Async.createList
is called once, but I want to be able to create multiple lists from different target attributes from the same request, and this is where it fails.
Ideally, the lists would be appended to the Async.lists
object so that they can be used outside of the Async
object. Right now, when I call Async.createList
multiple times, only the last call appends to 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
}
},
}
I am creating the object and calling the methods like this:
var github = new Async("https://api.github.com/users/john/repos")
github.create();
github.createList("name");
github.createList("id");
And then trying:
github.lists
You are re-assigning the function for this.req.onload
every time you call github.createList
.
i understand you want to do things after the request is loaded using req.onload
, but you are assigning a new function everytime, so the last assigned function will be called.
You need to remove the onload
function within Async.createList
Call github.createList("name");
only after the request is loaded as follows
var github = new Async("https://api.github.com/users/john/repos")
github.create();
github.req.onload = function () {
github.createList("name");
github.createList("id");
}
The answer is painfully simple. All I needed to do was get rid of the onload
function within Async.createList
and simple call Async.createList
in the callback of Async.create
createList : function(target) {
var self = this
var bits = []
var list = self.response(true)
for(obj in list){
bits.push(self.response(true)[obj][target])
}
self.lists[target] = bits
},
Using this to instantiate:
var github = new Async("https://api.github.com/users/john/repos")
github.create(callback);
function callback(){
github.createList("name");
github.createList("id");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.