【发布时间】:2013-02-23 12:01:36
【问题描述】:
这是一个有点难以言说的问题。基本流程如下:
- 一个类被实例化了。
- 这个类的构造方法然后实例化另一个类
- 这个新类的构造方法使用全局对象的方法来发出 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);
【问题讨论】:
标签: javascript ajax oop callback prototype