我有一个搜索输入,它通过 Ajax 侦听keyup
并change
触发列表视图的更新。
看起来像这样:
input.on('keyup change', function(e) {
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout( function() {
timer = null;
val = input.val();
el = input.closest('ul');
// run a function - triggers Ajax
widget[func](dyn, el, lib_template, locale, val, "update");
}, interval );
});
一切都很好,除了超时和绑定的处理,这会导致放置双 Ajax 请求而不是单个 Ajax 请求(当keyup
已经通过时,change
事件再次触发相同的 Ajax 请求)。
我可以通过添加另一个超时来“解决”这个问题:
var runner = false;
input.on('keyup change', function(e) {
if ( runner === false ){
runner = true;
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout( function() {
timer = null;
val = input.val();
el = input.closest('ul');
widget[func](dyn, el, lib_template, locale, val, "update");
// ssh....
window.setTimeout( function(){ runner = false; },2500);
}, interval );
}
});
但这一点都不好看……
问题:
如何确保两个都触发的绑定,我需要的函数只运行一次?
编辑:
Ajax 调用在这里触发:
widget[func](dyn, el, lib_template, locale, val, "update");
它调用此函数来构建动态列表视图
buildListView : function( dyn,el,lib_template,locale,val,what ){
...
// this calls my AJax Config "getUsers"
$.parseJSON( dynoData[ dyn.method ](cbk, val, dyn.display) );
});
// config AJAX
getUsers: function(cbk, val, recs){
var form = "",
pullRetailers = ( val === undefined ? "" : val ),
service = "../services/some.cfc",
method = "by",
returnformat = "json",
targetUrl = "",
formdata = "...manually_serialized...,
successHandler = function(objResponse, cbk) {
cbk( objResponse );
};
// finally pass to the generic JSON handler
ajaxFormSubmit( form, service, formdata, targetUrl, successHandler, "yes", "", returnformat, cbk );
}
// generic AJAX
var ajaxFormSubmit =
function ( form, service, formdata, targetUrl, successHandler, dataHandler, errorHandler, returnformat, type ){
...
$.ajax({
async: false,
type: type == "" ? "get" : type,
url: service,
data: formdata,
contentType: 'application/x-www-form-urlencoded',
dataType: returnformat,
success: function( objResponse ){
if (objResponse.SUCCESS == true || typeof objResponse === "string" ){
dataHandler == "yes" ? successHandler( objResponse, override ) : successHandler( override );
}
},
error: function (jqXHR, XMLHttpRequest, textStatus, errorThrown) { }
});
}
但这对于如何防止这两个事件触发我的 Ajax 更新的实际问题并没有太大帮助。