2010-02-01 23 views
0

在下面的代碼中,我想調用方法OpenNextPage通過回調由功能從第三方API調用。該方法第一次被稱爲Corridor的類實例調用。在第一次調用之後,通過傳遞給方法的callBack再次調用該方法,直到Api函數getCorridors不再返回走廊。JavaScript類和上下文的問題

我發現一些關於執行上下文的問題。方法OpenNextPage應該始終在第一次執行的同一個上下文中執行(其中mC是持有此實例的對象)。但是這並沒有發生,OpenNextPage被調用在不同的上下文中。有任何想法嗎?

乾杯

function startExec() 
{ 
    var mC = new Corridor(); 
    mC.OpenNextPage(); 
} 

Corridor.prototype.OpenNextPage = function() 
{ 
    if(this.KeepLoading == false) 
    { 
     if(this.KeepLoadingTimer) 
      clearTimeout(this.KeepLoadingTimer);   

     return 0; 
    } 

    this.ShowLoadingCorridorMsg();   
    this.LoadPage(++this.LoadedPages, this.OpenNextPage, 3 * this.ItemsPerPage); 
} 

//******************************************************************************** 
//Private 
Corridor.prototype.LoadPage = function(page, callBack, pageSize) 
{ 
    var ref = this; 

    var mt = new MWsTraffic(); 
    var city = new MCity(); 

    city.name = cityList.getCurrentCity().name; 
    city.state = cityList.getCurrentCity().state; 

    var rr = new MResultRange(); 

    //This function is defined in a sort of public API available on the partner web site. 
    //So, as far as I know, the execution context will be changed and as of this point the 'this' will refer 
    //to another object, that's why I have a this reference in the ref variable. This is what I think 
    mt.getCorridors(city, rr, 
     function(cInfo) 
     { 
      if (cInfo == null) 
      { 
       ref.KeepLoading = false; 
       return null; 
      } 

      if((cInfo.recordCount == 0)) 
      { 
       ref.KeepLoading = false; 
       return null; 
      } 

      var e; 
      for (var i = 0; i < cInfo.recordCount; i++) 
      { 
       e = cInfo.corridor[i];     
       ref.totalCorridorsArray.push(new corridorContents(e.codCorridor, e.nameCorridor, e.levelCongested, e.point.x, e.point.y, false)); 
      } 

      if(callBack != null) 
      { 
       //Corridor.call(ref, callBack); 
       callBack(); // <---- here's is the problem. This callback which points to the OpenNextPage function is being executed in another context. 
          // I want to execute it in the same context OpenNextPage was called originaly (from inside startExec mC object) 
      } 
     } 
    );  
} 

回答

1

您應該使用某種形式的 「綁定」 設施。這將幫助你

function bind(context,fncname){ 
    return function(){ 
     context[fncname].apply(context,arguments);  
    } 
} 

var openNextPage = bind(this,"OpenNextPage"); 
this.LoadPage(++this.LoadedPages, openNextPage, 3 * this.ItemsPerPage); 

或代替回調做

callBack.call(ref); 

但「綁定」是更好的,有時你想傳遞迴調到沒有指針「這」一些外面的功能引起。所以通過綁定它們,你將永遠有一個正確的範圍。

+0

好東西,確實有效。乾杯 – Andres 2010-02-01 14:23:41