这是一个难以理解的问题。这是基本过程:
一旦ajax请求完成,我想调用步骤#1中类的方法。实现这一目标的好方法是什么?
以下是我正在尝试做的事情: 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);
答案 0 :(得分:1)
在我看来,这是一个更广泛的架构问题,但这是可行的。
$.get
返回一个XHR对象,您可以使用返回值并挂钩其“成功”。
您可以将globalAction
更改为
globalAction: function(theUrl){
return globallyDoStuff.somethingWithACallback(theUrl);
}
然后将SomeClass
构造函数更改为
var SomeClass = function(theUrl){
var result = this.globalAction(theUrl);
//note, you now fill the object here, in the returned part
//when a constructor returns an object it behaves like a normal function
return {callRes:result,...};
};
然后将addSomeClass更改为
addSomeClass: function(theUrl){
var addedClass = new SomeClass(theUrl);
this.arrayOfClasses.push(addedClass);
addedClass.callRes.done(function(){
//your code executes here! EACH TIME AN AJAX REQUEST IS COMPLETED
}
},
注意,您还可以使用jQuery
全局ajaxComplete
方法:
$.ajaxComplete(function(){
//this executes whenever ANY AJAX request is complete!
}
您可以向其添加if
项检查,请参阅the API