问题
I have series of interactive sliders that change calculated values.
The calculations run on every tiny move of a dragged handle (via mousedown or touch drag event).
I need to update a database with the values but would prefer only to grab the values after the user "drops" the handle.
How can I determine if a finger or mouse is down, in order to skip the AJAX call?
function handleIsBeingDragged() {
// calculations based on all the input values here
// pseudo-code to check for mouseup event
if (mouseUp) {
// save only if mouse is now up - to avoid hundreds of updates per drag event
$.ajax();
}
}
回答1:
You need to add a bit of hysteresis to your code.
It happens I wrote a generic debounce
function for another answer here on SO which would be useful for this.
Here's how you'd use it:
function saveTheData() {
$.ajax(); ///
}
var saveTheDataDebounced = debounce(50, saveTheData);
function handleIsBeingDragged() {
saveTheDataDebounced();
}
The debounce
function:
// debounce - debounces a function call
//
// Usage: var f = debounce([guardTime, ] func);
//
// Where `guardTime` is the interval during which to suppress
// repeated calls, and `func` in the function to call.
// You use the returned function instead of `func` to get
// debouncing;
//
// Example: Debouncing a jQuery `click` event so if it happens
// more than once within a second (1,000ms), subsequent ones
// are ignored:
//
// $("selector").on("click", debounce(1000, function(e) {
// // Click occurred, but not within 1000ms of previous
// });
//
// Both `this` and arguments are passed through.
function debounce(guardTime, func) {
var last = 0;
if (typeof guardTime === "function") {
func = guardTime;
guardTime = 100;
}
if (!guardTime) {
throw "No function given to debounce";
}
if (!func) {
throw "No func given to debounce";
}
return function() {
var now = +new Date();
if (!last || (now - last) > guardTime) {
last = now;
return func.apply(this, arguments);
}
};
}
回答2:
You could assign the AJAX call to the "mouseup" event instead. In jQuery mobile "vmouseup".
来源:https://stackoverflow.com/questions/17707554/how-can-i-only-run-an-ajax-call-on-change-when-the-mouse-or-finger-is-no-longe