当鼠标(或手指)不再拖动时,我怎样才能在更改时运行AJAX调用?

时间:2013-07-17 18:32:39

标签: javascript jquery ajax mouseevent drag

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

计算在拖动手柄的每一个小动作上运行(通过mousedown或触摸拖动事件)。

我需要使用值更新数据库,但更愿意在用户“删除”句柄后获取值。

如何确定手指或鼠标是否已关闭,以便跳过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();
    }
}

2 个答案:

答案 0 :(得分:3)

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

碰巧我为another answer here on 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);
    }
  };
}

答案 1 :(得分:0)

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