首页 > 解决方案 > 如何使用布尔标志跳过特定事件?

问题描述

我正在制作一个函数,它在单一on方法中组合了 2 个事件,以便更好、更轻松地进行控制、编辑,如下所示:

class EventManager {
  constructor($el) {
    this.$el = $el;
    this.mainSwitch = false;
    this.subSwitch = false;
    this.condition = (!this.mainSwitch && !this.subSwitch); // false false then
    this.condition2 = (!this.mainSwitch && this.subSwitch); // false true then
  }
  start(e) {
    if (this.condition) {
      console.log(e.type);
      this.mainSwitch = true;
      return false; // return keyword for end the function
    } else if (this.condition2) {
      this.mainSwitch = false;
      this.subSwitch = false; // Go back to the default statement.
      return false;
    }
    return false;
  }
  move(e) {
    if (this.mainSwitch == true && this.subSwitch == false) {
      console.log(e.type);
    }
  }
  end(e) {
    if (this.mainSwitch == true && this.subSwitch == false) {
      console.log(e.type);
      this.mainSwitch = false;
      this.subSwitch = true;
    }
  }
  apply() {
    this.$el.on('touchstart mousedown', (e) => {
      this.start(e);
    })
    $('html').on({
      ['touchmove mousemove']: (e) => this.move(e),
      ['touchend mouseup']: (e) => this.end(e)
    })
  }
}
var thatEvent = new EventManager($('#link'));
thatEvent.apply();
      a {
        width: 100%;
        height: 100px;
        border-radius: 10px;
        background-color: brown;
        font-family: Helvetica;
        display: flex;
        flex-flow: row;
        justify-content: center;
        align-items: center;
      }
    <a id="link" target="_blank" href="https://google.co.uk" draggable="false">
      Click/Touch and Drag/Swipe
    </a>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我添加了用于跳过特定的布尔标志,events group这是因为此代码在我元素mouseevents时运行两次。touch

问题是,布尔标志不会mousedown像我预期的那样跳过事件。管理后this.condition2回滚进行比较this.condition。然后开火console.log(e.type)

起初,我认为布尔标志可以跳过event. 因为我在比较完成后添加了return关键字if来切断功能。

此问题导致该mousedown事件将永久禁用。对于使用该mousedown事件,两个标志,this.mainSwitchthis.subSwitch都应该设置为,falses但在我管理之后touchstart,布尔值设置为falsetrue因此mousedown事件不能再使用。

有没有办法在javascript中使用布尔标志实际跳过事件?

标签: javascripteventsbooleanflagstouchstart

解决方案


的值this.conditionthis.condition2不会在您的事件中发生变化。

您只需更改mainswitchandsubswitch变量。这并不意味着你改变这两个也会改变this.condition变量。因为 this 的值initialization/contructor仅从

更好地将您的this.condition对象更改为函数以使其更具动态性。因此它将始终依赖于您的主开关和子开关


推荐阅读