경쟁 조건에서 jquery/때 수행 시퀀스가?
-
13-12-2019 - |
문제
나는 웹 applciation 에 따라 apache,php,js/jquery.의 하나의 모듈 응용 프로그램은 초기화면 문서로드됩니다.는 호출 시퀀스는 init()funcion 수행하는 작업의 수,다른 사람의 사이에 그것이 가져오는 두 html 대화 ajax 를 통해로 삽입하는 기존 페이지입니다.에 대한 참조는 그 대로 저장된 변수,그래서 내가 지정하지 않아도 jquery 선택기를 통해 스크립트만 단순히 그들을 사용 변수를 대신 합니다.이 잘 작동하는 것을 제외하고,거의 사례(현재 그리고...)이 변수는'undefined'하려고 할 때 바인딩하기 위해 요소의 내부에 가져 대화 상자를 재생할 수 있습니다.는 이상한 일입니다,그 외에 바인딩에 대화 상자를 사용할 수 있는 응용 프로그램을 통해.이것은 ajax 를 호출이 성공하지만,aparently 몇 가지 종류의 경쟁 조건,그래서는 이런 변수 설정 후에 바인드를 시도했다.
에 대한 이해 이야,일어나지 않기 때문에 바인딩에서 수행됩니다.행()의 일부인 경우()실행해야 합니다 후 ajax 의 검색을 대화 상자가 안에 완료할 때().
Aparently 나는 뭔가가 기본적인 여기에.누군가에 대한 힌트를까?
다음을 인용하는 코드에서 발췌 작업을 구현합니다.그들은 나타날 수 있는 구문으로 잘못되었으로 어떤 부분이지만,그것은 단지 때문에 제거하는 코드 부품 관련이 없는 여기에.이 unshortened 코드의 잘 작동합니다.
변수:
Shorty.Tracking.Dialog.List:{};
Shorty.Tracking.Dialog.Click:{};
초기화 시퀀스:
$(window).load(function(){
//...
var dfd = new $.Deferred();
$.when(
// load layout of dialog to show the list of tracked clicks
Shorty.Tracking.init()
).done(function(){
// bind actions to basic buttons
Shorty.Tracking.Dialog.List.find('#close').on('click',function(){
// ...
});
// ...
});
// ...
})
단축된 init 기능:
Shorty.Tracking.init:function(){
// ...
var dfd=new $.Deferred();
// two dialogs are used by this plugin
var dialogs={
'list': Shorty.Tracking.Dialog.List,
'click': Shorty.Tracking.Dialog.Click
};
// load dialogs from server
$.each(['list','click'],function(i,dialog){
if (...){
// ...
dfd.resolve();
}else{
// load dialog layout via ajax and create a freshly populated dialog
$.ajax({
type: 'GET',
url: OC.filePath('shorty-tracking','ajax','layout.php'),
data: { dialog: dialog},
cache: false,
dataType: 'json'
}).pipe(
function(response){return Shorty.Ajax.eval(response)},
function(response){return Shorty.Ajax.fail(response)}
).done(function(response){
// create a fresh dialog
// insert it alongside the existing dialogs in the top controls bar
$('#controls').append(response.layout);
switch (dialog){
case 'list':
Shorty.Tracking.Dialog.List=$('#controls #shorty-tracking-list-dialog').first();
break;
case 'click':
Shorty.Tracking.Dialog.Click=$('#controls #shorty-tracking-click-dialog').first();
} // switch
dfd.resolve();
}).fail(dfd.reject)
} // else
}); // each
return dfd.promise();
},
응답의 Bergi 관리를 분명히 제거래 문제입니다.지금까지 나는 감지할 수 없습니다 더 이상 실패했 바인딩 시도합니다.그러나 나는 할 수 없습을 따르는 제안 완전히:그의 대답에 그 제안을 제거하 switch 문서의 초기화 방법에의 호의 직접적인 할당합니다.이것은 확실히 훨씬 더 우아하지만 그것은 작동하지 않을 것이다.가 인상을 몇 가지 missunderstanding 내 옆에는 방법에 대해 javascript 처리를 참조 및/또는 함수에 저장된 변수이다.
어쩌면 당신은,Bergi,또는 다른 사람이 할 수있는 창고 설명이:
이것은 수정 된 초기화 방법 위에서:
init:function(){
if (Shorty.Debug) Shorty.Debug.log("initializing tracking list");
// check if dialogs already exist
if ( $.isEmptyObject(Shorty.Tracking.Dialog.List)
&& $.isEmptyObject(Shorty.Tracking.Dialog.Click) ){
// two dialogs are used by this plugin
var dialogs={
'list': Shorty.Tracking.Dialog.List,
'click': Shorty.Tracking.Dialog.Click
};
// load dialogs from server
var dfds=$.map(dialogs,function(obj,dialog){
// load dialog layout via ajax and append it to the collection of dialogs in the controls
return $.ajax({
type: 'GET',
url: OC.filePath('shorty-tracking','ajax','layout.php'),
data: { dialog: dialog},
cache: false,
dataType: 'json'
}).pipe(
function(response){return Shorty.Ajax.eval(response)},
function(response){return Shorty.Ajax.fail(response)}
).done(function(response){
// create a fresh dialog and insert it alongside the existing dialogs in the top controls bar
$('#controls').append(response.layout);
// obj=$('#controls #shorty-tracking-'+dialog+'-dialog').first();
switch(dialog){
case 'list':
Shorty.Tracking.Dialog.List=$('#controls #shorty-tracking-list-dialog').first();
break;
case 'click':
Shorty.Tracking.Dialog.Click=$('#controls #shorty-tracking-click-dialog').first();
break;
} // switch
})
}) // map
return $.when.apply(null, dfds);
}else{
// dialogs already loaded, just clean them for usage
Shorty.Tracking.Dialog.List.find('#list-of-clicks tbody tr').remove();
new Deferred().resolve();
} // else
},
중간에 표시 할당 문을 주석으로 현재에 의해 대체 switch 문이 아래.나는 여러 가지 형태가 다음과 같 obj.요소와 그렇지만 실패했습니다.외부의 함수의 변수를 짧.추적이 있습니다.화입니다.목록 숏.추적이 있습니다.-화입니다.클릭 빈 상태를 유지합니다.
나는 절대 초보자를 웹 물건 ans js/jquery.그러나 나는 확실히 궁금하다 이것에 대해 자세히 알아보 취급 방법은 참조가 있습니다.
해결책
는 문제가 되는 코드:
var dfd=new $.Deferred();
$.each(['list','click'], function(){
...
dfd.resolve/fail();
});
당신이 하나만 만들이 지연이지만,그것을 해결하는 여러 번 있습니다.그래서 때 첫 번째 해결책을 발생,번째 Ajax 없었을 것이 완성된다.
그래서 대신 사용하여 두 Deferreds,그리고 그들을 결합을 통해 jQuery.when()
.또한,나는 생각하지 않을 만들어야 합니다 Deferreds 다.이 두 가지에서 얻 pipe()
호출합니다.
function init() {
var dialogs={
'list': Shorty.Tracking.Dialog.List,
'click': Shorty.Tracking.Dialog.Click
};
var deferreds = $.map(dialogs, function(obj, dialog) {
return $.ajax(...).pipe(...).done(...
// really, don't use switch here:
obj.element = response.layout;
}); // done() returns the Deferred
});
return $.when.apply(null, deferreds);
}
...
$.ready(function($) {
init().done(...);
});
OK,I 를 설명해야에 대해 스위치-Statement.그것의 진정한 값에 dialogs
객체를 할당됩에서[초기화되지 않은]변수를 개최하는 값(undefined
지)에 필드를 재지정의 Shorty
값은 변경되지 않습니다.기"포인터에서"자바 스크립트.생각만 그것이 유용할 것을 사용하여 현재 dialog
변수에 회원자는 대신 스위치의 문입니다.에 할당 Shorty.Tracking.Dialog.List
고 .Click
, 에,당신은 필요 같은 것을 사용
var dialogs = ["list", "click"];
var shortcut = Shorty.Tracking.Dialog; // some object
for (var i=0; i<dialogs.length; i++) {
// loop over them,
// do the ajax stuff
var element = $(repsonse.layout); // get the added element from the response
$('#controls').append(element);
shortcut[dialogs[i]] = element;
}
(결국 사용하는 코드 조각 어떻게 만들의 첫 글자는 대문자열에서 JavaScript?)