2

我有一系列更改计算值的交互式滑块。

计算在拖动手柄的每一次微小移动(通过鼠标按下或触摸拖动事件)上运行。

我需要用这些值更新数据库,但只希望在用户“放下”句柄后抓取这些值。

我如何确定手指或鼠标是否按下以跳过 AJAX 调用?

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();
    }
}
4

2 回答 2

3

您需要在代码中添加一些滞后。

碰巧我在 SO 上debounce为另一个答案写了一个通用函数,这对此很有用。

下面是你如何使用它:

function saveTheData() {
    $.ajax(); ///
}

var saveTheDataDebounced = debounce(50, saveTheData);

function handleIsBeingDragged() {
    saveTheDataDebounced();
}

debounce功能:

// 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);
    }
  };
}
于 2013-07-17T18:35:59.287 回答
0

您可以将 AJAX 调用分配给“mouseup”事件。在 jQuery 移动“vmouseup”中。

于 2013-07-17T18:36:39.270 回答