我正在尝试创建一个自动保存输入到几个文本框中的输入的功能。我在一个选择器 ($input) 中有 3 个输入,还有一个在 keyup/paste 和 keydown 上更新的计时器 (typingTimer)。如果在 keyup 事件之后计时器在 3 秒 (doneTypingInterval) 后没有被重置,元素将被发送到一个自动保存函数,该函数通过 ajax 发布元素名称和值。
我遇到的问题是,如果我输入一个输入(即:#input-name),一秒钟后我输入另一个(即:#input-shortName),第一个输入(#input-name)是从未发送到自动保存功能。有没有一种好的方法可以在不为每个输入创建唯一的 typingTimer 和 on 事件的情况下做到这一点?我以这种方式尝试过它并且它有效,但我确信必须有更好的方法。
let typingTimer;
const doneTypingInterval = 3000;
const $input = $('#input-name, #input-shortName, #input-email');
$input
.on('keyup paste', function () {
if($.fn.isAutoSaveOn()) {
clearTimeout(typingTimer);
typingTimer = setTimeout($.fn.autoSaving, doneTypingInterval, this);
}
})
.on('keydown', function () {
if($.fn.isAutoSaveOn()) {
clearTimeout(typingTimer);
}
})
;
$.fn.autoSaving = function(e) {
const autosave = $('#autosave')
if(autosave.hasClass('active')) {
autosave.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ' + lang_saving);
const element = $(e);
const url = '/v3/api/orgs/' + orgId + '/update';
const input = JSON.stringify({
field: element.attr('name'),
value: element.val()
});
$.ajax({
type: "POST",
url: url,
data: input,
contentType: "application/json"
})
.done(function(response) {
notify("Success", response, "bottom", "right", "ni ni-bell-55", "success", "animated fadeIn", "animated fadeOut");
})
.fail(function(response) {
notify("Error", response, "bottom", "right", "ni ni-bell-55", "error", "animated fadeIn", "animated fadeOut");
})
.always(function() {
$.fn.autoSaveOn();
});
}
}
函数式编程
慕尼黑5688855
相关分类