2012-12-10 32 views
2

我有一個表格,其中包含一個Repeater,它有一個RadioButtonList和一個TextBox。當用戶更改單選按鈕或其中一個文本框中的文本時,該Repeater項目的所選項目和關聯文本應保存到數據庫中。如何在javascript中手動運行setTimeout計時器?

保存在一個單選按鈕的變化是容易的,因爲.change()功能,但是對於TextBox我創建一個定時器,當用戶在2秒後保存數據文本更改停止輸入

的問題是,如果用戶在定時器執行之前離開頁面或開始在不同的文本框中輸入內容,則需要手動執行定時器。我怎樣才能做到這一點?

我的JavaScript看起來像這樣:

var typingTimer;    //timer identifier 
var doneTypingInterval = 2000; //time in ms, 2 second for example 

$('textarea').on('input', function() { 
    // Clear timer 
    clearTimeout(typingTimer); 

    // Set new timer to save form, passing current repeater item to Save method 
    var parent = $(this).closest('.my-repeater-section'); 
    typingTimer = setTimeout(function() { saveForm(parent); }, doneTypingInterval); 
}); 

回答

2

定時器僅僅是一個延遲的函數調用。因此,命名功能,你就可以「手動:」把它當用戶離開該文本區域會失去焦點

var typingTimer;    //timer identifier 
var doneTypingInterval = 2000; //time in ms, 2 second for example 

$('textarea').on('input', function() { 
    // Clear timer 
    clearTimeout(typingTimer); 

    // Set new timer to save form, passing current repeater item to Save method 
    var parent = $(this).closest('.my-repeater-section'); 

    function callback() { 
     saveForm(parent); 
    } 

    typingTimer = setTimeout(callback, doneTypingInterval); 

    // call it manually like usual: 
    // callback(); 
}); 
+0

謝謝,我仍然搞清楚JavaScript,並沒有意識到它只是一個延遲的函數調用,而不是一個實際的對象。 – Rachel

2

打電話給你的保存功能上的模糊,這樣,如果你聽那個事件你可以使用你的保存功能

$("textarea").blur(function(){ 
    //Call your save function here 
}); 
+0

雖然這確實爲我提供了一種更好的方法來完成我想要做的事情,但我接受了另一個答案,因爲它回答了我最初詢問的如何手動運行setTimeout的問題。不管怎麼說,這個+1是更好的方式來保存更改:) – Rachel

相關問題