2013-03-08 32 views
1

这是一个有点难以言词的问题。这里是基本的过程:回调类实例化另一个类使AJAX请求

  1. 一个类被实例化。
  2. 这个类的构造方法实例化另一个类
  3. 这个新类的构造方法使用一个全局对象的方法,使一个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); 

回答

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

相关问题