我正在为Canvas for Windows 10开发一个nodeJS游戏。 所以我用画布绘制了一个按钮。要使按钮有效,我在整个画布元素上都有一个 EventListener,并检查当前的 客户端鼠标位置。如何删除EventListener?
E.g
var obj = this;
canvas.addEventListener("click", function (e) { // Handle Click on Canvas
obj.clickEvent(e);
});
当我想删除按钮我叫this.del()
del() {
this.display = false;
var obj = this;
canvas.removeEventListener("click", function (e) {obj.clickEvent(e);});
delete this;
notification(2, "deletet" + this.text);
}
我使用obj
淡然this
的事件监听内将无法正常工作。
obj.clickEvent(e)
只是比较鼠标位置的坐标与按钮的坐标。这工作正常。
任何可以获得该工作的建议或想法?
我尝试了一些解决方法,但目前无法处理它。
的第一次尝试:
class Button {
constructor(container, func, x, y, w, h, bg_color = "#F18F26", text, font_size = 16, font_color = "#FFF", display = true) {
... // store parameters in this
var obj = this;
this.eventListener = canvas.addEventListener("click", function (e) { // Handle Click on Canvas
obj.clickEvent(e);
});
if (container !== false)
container.addCtx(this);
}
clickEvent(e) {
if ((e.clientX >= this.x - (this.w/2)) && (e.clientX <= this.x + (this.w/2)) && (e.clientY >= this.y - (this.h/2)) && (e.clientY <= this.y + (this.h/2))) {
//notification(1, "Glückwunsch");
_start.hide();
_game_over.hide();
switch (this.func) {
... // fires function
}
}
this.del();
}
draw() {
... // draws the button
}
del() {
this.display = false;
var handler = this.eventListener;
canvas.removeEventListener("click", handler);
delete this;
notification(2, "deleted" + this.text);
}
}
你应该使用lambda而不是存储'this'。 – SLaks