javascript - 如何使用布尔标志跳过特定事件?
问题描述
我正在制作一个函数,它在单一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.mainSwitch
和this.subSwitch
都应该设置为,falses
但在我管理之后touchstart
,布尔值设置为false
,true
因此mousedown
事件不能再使用。
有没有办法在javascript中使用布尔标志实际跳过事件?
解决方案
的值this.condition
也this.condition2
不会在您的事件中发生变化。
您只需更改mainswitch
andsubswitch
变量。这并不意味着你改变这两个也会改变this.condition
变量。因为 this 的值initialization/contructor
仅从
更好地将您的this.condition
对象更改为函数以使其更具动态性。因此它将始终依赖于您的主开关和子开关
推荐阅读
- python-3.x - Tkinter:为什么它会带来一个从类中获取的空变量?
- python - .pop() 同时影响两个列表
- python - Pandas - 根据之前的行为进行插值
- debugging - 将 c# dll 引入 c++ dll 后,Visual Studio 2017 会跳过所有调试点
- python - EC2 实例未连接到互联网
- node.js - NodeJS CSV Parse 库删除 JSON 中的 "
- python - 大熊猫的第 1 年时间戳
- c++ - 为什么在处理空值时 Visual Studio 代码不会抛出错误?
- arrays - 基于python中嵌套的多个条件过滤Json数组(没有根节点名称)
- c - 如何编译包含 glut 的 C 文件?