每次执行另一个功能之前如何检查一个功能是否已被调用

时间:2018-10-15 14:00:03

标签: javascript

我有一个HTML元素的onMouseDownEssence()和onMouseUpEssence()函数,如何在每次调用onMouseUpEssence()之前检查是否每次都调用过onMouseDownEssence()以确保我获得正确的鼠标按下位置?

这是鼠标按下功能:

var mouseDownIndex = -1;

function onMouseDownEssence(downIndex, e, className) {

    dragTarget = e.target;
    holdStarter = new Date().valueOf();

    mouseDownIndex = downIndex;
}

这是mouseup功能:

function onMouseUpEssence(upIndex, e, className) {

    var el = e.target;
    var holdActive = (new Date().valueOf() - holdStarter) > holdDelay;

    if (holdActive) {
        var thisUpTargetIndex = el.getAttribute("name");

        if (lastUpTargetIndex != null && thisUpTargetIndex != lastUpTargetIndex) {
            // console.log("double drag done");
            el.removeAttribute(dbl);
            lastUpTargetIndex = null;

            var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
                    className);

        } else {
            // console.log("drag done");
            var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
                    className);
        }

        holdActive = false;
    } else if (el.getAttribute(dbl) == null) {
        el.setAttribute(dbl, 1);
        setTimeout(
                function() {
                    if (el.getAttribute(dbl) == 1 && !dragTarget) {
                        if (e.button === 0) {
                            // console.log("single clicked ");
                            el.removeAttribute(dbl);

                            var selectedText = clickAutoExpand(upIndex,
                                    className);

                        }
                    } else {
                        if (el.getAttribute(dbl) != null)
                            lastUpTargetIndex = el.getAttribute("name");
                    }
                }, dblDelay);
    } else {
        // console.log("double clicked");
        el.removeAttribute(dbl);

        var selectedText = clickAutoExpand(upIndex, className);
    }

    dragTarget = null;

}

1 个答案:

答案 0 :(得分:2)

我的方法是跟踪mouseDownEssence()是否被调用。如果没有,请在继续操作之前先调用它。这种方法将在以下方面起作用。异步函数的工作原理有所不同,但mouseDownEssence()似乎是同步函数。

let isMouseDownEssenceCalled = false;

function mouseDownEssence() {
  isMouseDownEssenceCalled = true;

  ...
}

function mouseUpEssence() {
  if (!isMouseDownEssenceCalled) {
    mouseDownEssence()
  }

  ...

  isMouseDownEssenceCalled = false;
}