【发布时间】:2019-04-11 07:23:31
【问题描述】:
我正在制作一个函数,将 2 个事件组合在单个 on 方法中,以便更好、更轻松地控制、编辑,如下所示:
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。因为我在每个if部分添加了return关键字,用于在比较完成后切断功能。
此问题导致mousedown 事件将永久禁用。为了使用mousedown 事件,this.mainSwitch 和this.subSwitch 这两个标志都应该设置为falses 但在我管理touchstart 之后,布尔值设置为false 和true 所以@987654343 @event 不能再使用了。
有没有办法在 javascript 中使用布尔标志来实际跳过事件?
【问题讨论】:
-
this.condition和this.condition2的值不会在您的事件中发生变化......您只需更改mainswitch和subswitch变量。这并不意味着您更改这两个也会更改this.condition变量。因为 this 的值仅从初始化/构造函数中设置 -
最好将您的
this.condition对象更改为函数以使其更具动态性。因此它将始终依赖于您的主开关和子开关 -
@JohnChristianDeChavez :o 我认为
constructor的值会在我在函数内部使用它时改变它。根据您的建议,它可以按我的意愿工作。非常感谢 -
不,构造函数只在你初始化类后运行。
标签: javascript events boolean flags touchstart