2 つの入力テキスト フィールドと 1 つの [保存] ボタンがあります。
<input type="text" id="myInput" />
<input type="text" id="searchResult"/>
<button id="myButton>save</button>
myInput
テキスト フィールドにはonchange イベントがあり、Ajax リクエストを送信してデータを取得し、結果をsearchResult
テキスト フィールドに表示します。
保存ボタンには、空の文字列などのテキスト フィールドの入力を検証するクリック イベントがあります。searchResult
OK の場合は、保存に進みます。
$("myInput").change(function() {
var userInput = $("myInput").val(); //get value from the text field
var responseText = callAjaxToGetData(userInput): //XHR request to get some data
$("searchResult").val( responseText ); //show the XHR result here
});
$("myButton").click(function() {
var searchResultField = $("searchResult").val(); //get value from the searchResult field
var isOK = validate(searchResultField); //check empty string and such
if(isOK) { saveDataViaAjax(userInput); }
});
問題
ユーザーがテキスト フィールドにテキストを入力し、"save"
ボタンをクリックすると、
onchange event
トリガーされ、callAjaxToGetData()
呼び出されます。(XHR)before
callAjaxToGetData()
が完了し、searchResult テキスト フィールドに入力すると、myButtononclick event
がトリガーされます。onclick イベント ハンドラー側で、searchResult フィールドがまだ空であるため、検証が失敗します。
callAjaxToGetData()
最後に終了し、searchResult テキスト フィールドに入力します。
理想的には、callAjaxToGetData() が最初に完了してから onclick イベント内のプロセスに進み、検証が失敗しないようにします。
これは、人々が直面する非常に一般的なケースのように思われるので、皆さんはこの問題にどのように取り組んでいるのだろうか?
以下のようにonclickイベントに間隔を入れようと考えています(これにはresponseTextがグローバル変数である必要があります)
$("myButton").click(function() {
var interval = setInterval(function() { //call every 500ms
//if responseText is not null that means i know the ajax inside of onchange event is completed for sure.
if( responseText != null ) {
clearInterval(interval);
var searchResultField = $("searchResult").val(); //get value from the searchResult field
var isOK = validate(searchResultField); //check empty string and such
if(isOK) { saveDataViaAjax(userInput); }
}
}, 500);
});