如何使用布尔标志跳过特定事件?

问题描述 投票:0回答:1

我正在制作一个功能,将单个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中使用布尔标志实际跳过事件?

javascript events boolean flags touchstart
1个回答
1
投票

this.conditionthis.condition2的价值在您的活动中没有变化。

你只改变了mainswitchsubswitch变量。它并不意味着你改变那两个将改变this.condition变量。因为这个值只是从initialization/contructor设定的

更好地将您的this.condition对象更改为一个函数,使其更具动态性。所以它总是依赖于你的主开关和子开关

© www.soinside.com 2019 - 2024. All rights reserved.