2011-11-28 1 views
1

자바에서 동일한 메소드 methMain을 호출해야하는 일부 메소드 (methA, methB ...)가 있습니다. 이 메서드 methMain 다음 일부 데이터를 가져올 필요가 및 호출 할 메서드 (methA 또는 MethB ...) 콜백 않습니다. How can I pass a reference to a function, with parameters?동일한 범위를 사용하는 매개 변수가있는 메소드에 대한 참조를 자바 스크립트로 작성하십시오.

그 해결책, 그리고 내가 본 모든 사람들은, 현재 범위에서 작동하지 않는 것 :

나는 성공적 여기에 기록 된 것을 사용하여 방법에 대한 포인터/참조를 만들 수 있습니다. 이 코드는 작동하지 않습니다 변수 this.gotData가 설정되지 않습니다

function TestStructure() { 

    this.gotData = false; 

    //define functions 
    this.methA = function (parA) { }; 
    this.methB = function (parb) { }; 
    this.createFunctionPointer = function (func) { }; 


    this.createFunctionPointer = function (func /*, 0..n args */) { 
     var args = Array.prototype.slice.call(arguments, 1); 
     return function() { 
      var allArguments = args.concat(Array.prototype.slice.call(arguments)); 
      return func.apply(this, allArguments); 
     }; 
    }; 

    this.methA = function (parA) { 

     alert('gotData: ' + this.gotData + ', parA: ' + parA); 

     if (this.gotData == false) { 
      var fp = this.createFunctionPointer(this.methA, parA); 
      this.methMain(fp); 
      return; 
     } 

     //...do stuff with data 
    } 

    this.methB = function (parB) { 

     alert('gotData: ' + this.gotData + ', parB: ' + parB); 

     if (this.gotData == false) { 
      var fp = this.createFunctionPointer(this.methB, parB); 
      this.methMain(fp); 
      return; 
     } 

     //...do stuff with data 
    } 

    this.methMain = function (func) { 

     //...get some data with ajax 

     this.gotData = true; 

     //callback to function passed in as parameter 
     func(); 
    } 
} 

var t = new TestStructure(); 
t.methA('test'); 

methMain가 FUNC (methA 또는 methB)에 콜백을한다.

이 문제에 대한 해결책이 있습니까? 아니면 디자인을 다시 생각해야합니까? async로 차단하지 않고 ajax로 데이터를 가져 오려면이 작업을 수행하고 싶습니다. false.

답변

0

나는 100 % 확신하지만 난 당신이 함수 포인터를 만들어 같은 this 호출 할 수

this.createFunctionPointer = function (func /*, 0..n args */) { 
    var args = Array.prototype.slice.call(arguments, 1); 
    var that = this; //<<< here 
    return function() { 
     var allArguments = args.concat(Array.prototype.slice.call(arguments)); 
     return func.apply(that, allArguments); 
        //here ^^^ 
    }; 
}; 

이것은 당신의 부분적 평가 기능을하게됩니다를 수행하여 문제를 해결할 수 있다고 생각합니다. 다른 범위를 원하면 .apply에 전달하는 값을 변경하십시오.

+0

입력 해 주셔서 감사합니다. 현재 작동하고 있습니다. 여기 게시하기 전에 시도한 이후 다소 당혹 스럽습니다. :-) – AxAn

관련 문제