2014-10-03 5 views
4

말은 내가 문제가 APPEND를 호출하기 전에 AJAX 호출되는 비동기가 완료되지 것입니다 JS연기 프로토 타입 기능

function UnitTable(options){ 
    this.name = options.name; 
} 

UnitTable.prototype = { 
    query : function(){ 
    $.post('php.php', { func : "get" }, function(data){ 
     if (data) this.data = data; 
    }); 
    return this; 
    }, 

    append : function(){ 
    $('#result').append(this.data); 
    } 
} 

var unitTable = new UnitTable(options).query().append(); 

에서 클래스를 만들 수 있습니다.

$ .Deferred()를 사용해 보았지만 reutrn deferred.promise()와 같이 올바르게 반환 할 수 없으며 체인화 된 이벤트를 계속 진행할 수 없습니다.

답변

3

당신은 그렇게 할 수 없어,하지만 당신은 query에 약속 값을 설정하고 append의 콜백을 처리 할 수 ​​

UnitTable.prototype = { 
    query: function() { 
    this.queryPromise = $.post('php.php', {func: "get"}); 
    return this; 
    }, 
    append: function() { 
    this.queryPromise.done(function(data) { 
     $('#result').append(data); 
    }); 
    return this; 
    } 
}; 

new UnitTable(options).query().append(); 
+0

감사합니다. 계속 진행하는 것이 좋은 방법이라고 생각하십니까? – Tester232323

+0

나는 괜찮다고 생각 하긴하지만 제어 흐름을 알아야한다. 해당 줄은 코드의 다음 줄보다 먼저 실행되지 않습니다. – elclanrs

+0

아니요, 진행하기에 좋지 않습니다. 'UnitTable (options) '의 인스턴스에 대한 참조가 유지되면, 이전 요청이 해결되기 전에'query()'메소드를 호출 할 수 있습니다. 그러나 단 하나의'this.queryPromise' 만 있으면 모든 요청이 그것을 "공유"해야합니다. 해결되어야 할 마지막 요청이 전투에서 승리 할 것입니다. 어떤 요청이 먼저, 마지막 또는 그 사이에 있을지 아무런 보장이 없습니다. 마지막 요청은 반드시 보장 된 빅터가되어야한다는 가정하에,'query()'가 새로운 요청을하기 전에 이전 요청을 취소해야한다. –

1
당신은 @elclanrs suggested 같은 일반 약속을 할 수

; 위의 구조를 대부분 유지할 수있는 대안은 콜백 목록을 사용하는 것입니다. jQuery는 callbacks과 함께 멋진 관리 방법을 제공합니다.

function UnitTable(options){ 
    this.name = options.name; 
    this._appendCallbacks = $.Callbacks("once memory"); 
} 

UnitTable.prototype = { 
    query : function(){ 
    $.post('php.php', { func : "get" }, function(data){ 
     if (data) this.data = data; 
     this._appendCallbacks.fire(); 
    }); 
    return this; 
    }, 

    append : function(){ 
    this._appendCallbacks.add(
     $.proxy(function() { $('#result').append(this.data); }, this) 
    ); 
    } 
} 

var unitTable = new UnitTable(options).query().append();