我正在制作一个功能,将单个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
和subswitch
变量。它并不意味着你改变那两个将改变this.condition
变量。因为这个值只是从initialization/contructor
设定的
更好地将您的this.condition
对象更改为一个函数,使其更具动态性。所以它总是依赖于你的主开关和子开关