1
这是一个有点难以言词的问题。这里是基本的过程:回调类实例化另一个类使AJAX请求
- 一个类被实例化。
- 这个类的构造方法实例化另一个类
- 这个新类的构造方法使用一个全局对象的方法,使一个AJAX请求。
一旦ajax请求完成,我想调用在步骤#1中的类上的方法。什么是实现这一目标的好方法?
这里是我想要做的jsfiddle: http://jsfiddle.net/twiz/3PRma/4/
同样的代码如下:
//The global object that makes an ajax call
///////////////////////////////////////////////
globallyDoStuff={
somethingWithACallback: function(url,callback){
$.get(url,{},function(){
// WHAT do I do here to call the
// "doSomethingToAllTheClasses" method?
});
}
}
// A class used to hold an array of classes
///////////////////////////////////////////////
var SomeClassCollection = function(arrayOfURLs){
this.arrayOfClasses=[];
for(var i=0;i<arrayOfURLs.length;i++){
this.addSomeClass(arrayOfURLs[i]);
}
};
SomeClassCollection.prototype={
addSomeClass: function(theUrl){
this.arrayOfClasses.push(new SomeClass(theUrl));
},
doSomethingToAllTheClasses: function(){
// I WANT TO CALL THIS EACH TIME AN AJAX REQUEST IS COMPLETED
console.log(this.arrayOfClasses);
}
}
//The class that calls the global ajax object's method
///////////////////////////////////////////////
var SomeClass = function(theUrl){
this.globalAction(theUrl);
};
SomeClass.prototype={
globalAction: function(theUrl){
globallyDoStuff.somethingWithACallback(theUrl);
}
}
//List of urls
///////////////////////////////////////////////
var urls=[
"/echo/json/",
"/echo/json/",
"/echo/json/",
"/echo/json/",
"/echo/json/",
]
//Create the instance
///////////////////////////////////////////////
var someInstance = new SomeClassCollection(urls);