我正在爲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