2014-05-12 2 views
0

내가 가지고 다음과 같은 방식으로 부하 요청하는 일련의 호출 경로 : 나는 다른 경로로 전환하는 경우 이러한 요청을 취소 할 수있는 방법이 있나요다른 경로로 전환 할 때 요청의 Sammy.RenderContext 시퀀스를 중단 하시겠습니까?

this              
    .load('/url/to/template.html') 
    .then(function(html) {                       

    })                 
    .load('/url/to/partial/template.html') 
    .then(function(html) { 

    })                 
    .load('/url/to/partial/template.html')  
    .then(function(html) { 

    })                 
    .load('/url/to/json', {json: true}) 
    .then(function(data){            

    }); 

?

답변

0

다른 경로로 전환하면 Sammy에 비동기 요청을 중단 할 수있는 방법이 없습니다. 당신이 할 수있는 최선의 방법은 콜백으로 돌아온 후에 비동기 요청에 의해로드 된 데이터의 처리를 중단하는 것입니다. 내가 전역 객체를 사용하는 방법은 코드 실행을 시작한 이후 변경되었는지 확인할 수있는 전역 객체를 사용하는 것입니다.

window.currentRoute = null; 
Sammy.get('#/some/path/here', function() { 
    // This should be an object because that way we can take advantage of 
    // Reference Type equality. However, it doesn't matter what is put in 
    // here, and could easily just be "new Object()". 
    var localCurrentRoute = { 
     'currentPath': '#/some/path/here' 
    }; 
    // If you don't always want to override the current route, put some logic 
    // before this assignment. 
    window.currentRoute = localCurrentRoute; 
    this.load('/url/to/template.html').then(function(html) {                       
     // Check if the route is the same object as what we started with, and 
     // if not, abort further processing of this resource. 
     if(window.currentRoute !== localCurrentRoute) { 
      return; 
     } 
     // ... do stuff here 
    }); 
}); 

이 코드를 사용하면 새 경로를로드 할 때마다 전역이 가리키는 개체를 변경해야합니다. 참조 유형 동등성을 사용하여 경로가 시작된 경로가 아닌 경우 우리는 경로가 아래에서 변경되었음을 알고 비동기 적 load(). then() 메소드는 데이터를 더 이상 처리하지 않습니다. 그러나 이것은 비동기 로딩 (컨텍스트가 변경되는 상황)과 관련된 대부분의 문제를 해결하지만 대부분의 경우 일반적으로 충분합니다.

그러나 이것은 데이터로드를 멈추지 않습니다. 기본적으로 Sammy에서는 수행 할 수 없습니다. 특히 긴 실행 요청이있는 경우 대체 비동기 라이브러리를 살펴볼 수 있으며 위의 코드는 새 비동기 호출이로드 될 때마다 중단되는 각 비동기 호출에 대한 참조를 저장하도록 수정되어야합니다. 나는 그들이 좋아하는 도서관과 함께 할 수있는 운동으로 떠날 것이다.

0

빌드 옵션이 없지만 약간의 해결 방법을 만들었습니다. 에서 sammy.js :

(function ($) { 
 

 
var Sammy, 
 
    currentXhr = null //Added this var 
 

 
.... 
 

 
// added this method to abort ajax call 
 
abort: function() { 
 
      if (currentXhr) { 
 
       currentXhr.abort(); 
 
       currentXhr = null; 
 
      } 
 
     }, 
 
     
 
load: function (location, options, callback) { 
 
       var context = this; 
 
       return this.then(function() { 
 
        .... 
 
        this.wait(); 
 
         
 
        //abort any current call 
 
        this.abort(); //Added this row 
 
         
 
        currentXhr = $.ajax($.extend({ //added 'currentXhr =' 
 
        ...

관련 문제