How can I only run an AJAX call on change when the mouse (or finger) is no longer dragging?

前提是你 提交于 2019-12-22 00:36:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!