2017-08-02 150 views
-2

我正在爲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); 
    } 
} 
+0

你應該使用lambda而不是存儲'this'。 – SLaks

回答

0

編輯

在你的構造:

this.eventListener = this.clickEvent.bind(this); 
canvas.addEventListener('click',this.eventListener); 

在你del

canvas.removeEventListener('click',this.eventListener); 
this.eventListener = null; 

此外,這是沒用的,做delete thisdel方法裏面,一個實例C註釋刪除自己。你所能做的就是讓實例有資格進行垃圾回收,方法是確保沒有其他東西保存對實例的引用。

ORIGINAL

你需要保持到處理程序的引用:

var obj = this; 
var handler = obj.clickEvent.bind(obj); 

canvas.addEventListener('click',handler); 

...後來

canvas.removeEventListener('click',handler); 

檢查MDNremoveEventListener文檔

+0

好吧,看起來很簡單,我會嘗試 –

+0

全部回答的Downvotes(這些都是相同的答案)讓我感到驚訝,我的意思是,有592k代表的人得到了downvoted?請記住'handler'的範圍,以便在'del'方法中可以訪問它。 – Adam

+0

投了所有答案備份,請觀看我的編輯。該變量似乎爲null或未定義,其中存儲處理程序。 –

0

要刪除的是不同的函數,它無關,與你實際添加的監聽器。

您需要將實際的原始偵聽器存儲在某個變量中,以便稍後將其刪除。

+0

投訴所有答案備份,請觀看我的編輯。該變量似乎爲null或未定義,其中存儲處理程序。 –

+1

@DOCTYPEHTML:這是因爲'canvas.addEventListener'實際上並沒有返回任何東西。您需要存儲處理程序本身。 – SLaks

0

您必須刪除相同的偵聽器對象,在這種情況下是相同的功能。

window.addEventListener('click', windowClickEvent); 

function windowClickEvent(e) { 
    // ... 
} 

這裏windowClickEvent函數被綁定到一個click事件。要刪除監聽器,您必須通過與綁定的函數相同的函數。

window.removeEventListener('click', windowClickEvent); 
+0

投了所有答案備份,請觀看我的編輯。該變量似乎爲null或未定義,其中存儲處理程序。 –