2012-02-09 3 views
1

개별 요청 자체가 아닌 모든 아약스 요청에서 onComplete 이벤트를 수신 대기합니다.아약스 요청이 완료되면 이벤트 발생

모든/모든 아약스 요청이 완료되면 이벤트를 시작하고 싶습니다.

이것이 가능합니까? 사전에

감사합니다, 팀

편집 : 전용 (V1.4) LIB 요구 사항 Mootools의

답변

3

:

$(document).ajaxComplete(function() { 
    $(this).text('Triggered ajaxComplete handler.'); 
}); 

은 한 번보세요. 코드는 아주 간단합니다. 이것은 당신이가는 어느 방법이 동일합니다 -

// enable log func... 
Class.refactor(Request, { 
    success: function(text, xml){ 
     this.previous(text, xml); 
     Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
    }, 
    failure: function(){ 
     this.previous(); 
     Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
    } 
}); 

과 공통 비트 : 하나의 요청 프로토 변화에 대한 내 선택이 가능한 경우, Mootools의-부터 Class.refactor 될 것이다.

// assign a logger function 
Request.monitor = function() { 
    console.log("onComplete", this.response.text); 
}; 

// call a simple request object. 
new Request({ 
    url: "/echo/html/", 
    method: "post", 
    data: { 
     html: "hello" 
    } 
}).send(); 

이유 : mootools-core 변경과 독립적으로 작동합니다. 당신은 대신 implement을 통해 클래스를 변경할 수 있습니다

미래에 API의 변화가 아니라면 그것은, 원래 후 우리를 실행은 FUNC 코드가 무엇인지 상관하지 않고 파괴되지 않습니다이 원 '생각 그러나 mootools-core의 변경 사항을 설명합니다. 실제로 의미 복사 방법에 현재 FUNC를 붙여 넣은 추가 - 다행히 짧은 방법은 우리가 MOD하려면 :

Request.implement({ 
    success: function(text, xml){ 
     this.onSuccess(this.processScripts(text), xml); 
     Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
    }, 
    failure: function(){ 
     this.onFailure(); 
     Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
    } 
}); 

을 그리고 마지막으로, 당신도 당신의 일을, 기존의 낮은 수준 var oldsuccess = Request.prototype.success을 절약 할 수 있습니다 및 oldsuccess.apply(this, arguments)입니다.

HTML 및 JSON과 같은 요청의 하위 클래스가 어렵습니다. 이미 정의 된 경우 이전 프로토 타입이 복사되어 로거에서 수행됩니다. 대신 작은 객체로 이것을 수행하여이를 모든 요청 클래스에 구현할 수 있습니다.

이런 식으로 뭔가 우아하고 일을하지만 성공의 방법은, 다른 코드에서 동일한 경우에만 수 있습니다 - 그것은 서브 클래스에서 물건을 깰 것이다

(function() { 
    var changes = { 
     success: function(text, xml){ 
      this.onSuccess(this.processScripts(text), xml); 
      Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
     }, 
     failure: function(){ 
      this.onFailure(); 
      Request.monitor && typeof Request.monitor == "function" && Request.monitor.apply(this, arguments);    
     } 
    }; 

    [Request, Request.HTML, Request.JSON].invoke('implement', changes); 
})(); 

마지막 방법 + 오리지널 프로토의 콤보은 무엇입니까 당신은 성공 함수가 모든 3에 걸쳐서 다르기 때문에 정말로 필요합니다 ...

편집 이것은 우스꽝스러워지고 있습니다. 내가 말했듯이, 가장 쉬운 작업이 아니었다. ...

이것은 내가 생산에서 사용할 최종 버전/리팩터가 될 것이고, 모든 3 가지 클래스로 테스트하고 작업 할 것이다. JSON 또는 HTML에 대한 추가 구문 분석이 수행되기 전에 완료된 메서드가 있다는 것을 기억하십시오. 낮은 수준의 로깅입니다. 그렇지 않으면 리팩토링자가 계속해서 액세스하고 실패하면 대신에 실패합니다.

(function() { 
    // what we will extend 
    var classes = [Request, Request.HTML, Request.JSON], 
     // map to a text name 
     mapper = ["Request", "Request.HTML", "Request.JSON"], 
     // store reference to original methods 
     orig = { 
      onSuccess: Request.prototype.onSuccess, 
      onFailure: Request.prototype.onFailure 
     }, 
     // changes to protos to implement 
     changes = { 
      onSuccess: function(){ 
       Request.Spy && typeof Request.Spy == "function" && Request.Spy.apply(this, arguments); 
       orig.onSuccess.apply(this, arguments); 
      }, 
      onFailure: function(){ 
       Request.Spy && typeof Request.Spy == "function" && Request.Spy.apply(this, arguments); 
       orig.onFailure.apply(this, arguments); 
      } 
     }; 

    classes.invoke('implement', changes); 

    // allow us to tell which Class prototype has called the ajax 
    Request.implement({ 
     getClass: function() { 
      var ret; 
      Array.each(classes, function(klass, index) { 
       if (instanceOf(this, klass)) { 
        ret = mapper[index]; 
       } 
      }, this); 
      return ret; 
     } 
    }); 
})(); 

// to enable spying, just define Request.Spy as a function: 
Request.Spy = function() { 
    console.log(this.getClass(), arguments); 
}; 

// test it via normal Request 
new Request({ 
    url: "/echo/html/", 
    data: { 
     html: "normal data"  
    } 
}).send(); 


// test via HTML 
new Request.HTML({ 
    url: "/echo/html/", 
    data: { 
     html: "<p>normal data</p>"  
    } 
}).send(); 

// test via JSON 
new Request.JSON({ 
    url: "/echo/json/", 
    data: { 
     json: JSON.encode({'normal':'data'})  
    } 
}).send(); 

jsfiddle : 내가 Mootools의 찾고 있어요 jQuery를위한 http://jsfiddle.net/dimitar/3rnKe/

+0

항상 당신이 남자 인 것처럼 Dimitar! 휴식을 가져 주셔서 감사합니다. THX를 다시 테스트하고 다시 게시 할 예정입니다. –

+2

의 ok는 나에게 내 블로그에 넣을 물건을 더 준다 :) –

+0

final 버전에서 나는 proto.implement를 Klass.implement로 바꿨고 모든 것이 훌륭하게 작동한다. Request, Request.HTML, Request.JSON으로 테스트되었습니다. 이 Request.monitor를보고있는 사람은 요청 객체를 함수 안에 "this"로 전달할 것이고, 여러분은 사용할 수있는 모든 것을 갖게 될 것입니다. 다시 한 번 감사드립니다! –

0

편집 : 솔루션 jQuery를 작동합니다. MooTools가 아닙니다. 당신이와 절편 만 관찰 하려는 경우가 까다로울 수 http://api.jquery.com/ajaxComplete/

+0

죄송합니다 남자. –

+0

그러나 mootools에 이미 존재하지 않는 포트에 체크 아웃하는 것이 좋습니다. –

+0

와우. 미안해. .. 나는 마크를 조금 빨리했고, mootools 태그를 놓쳤다. – osahyoun

관련 문제