天天看點

removeEventListener解綁不了使用了bind()事件

這個算是我在偶爾中發現的一個問題,因為最近都喜歡使用

class

來寫,是以這個裡面的

this

感覺亂飛,最近就因為一個綁定事件讓我搞不懂,我這裡就寫了一個簡單的demo來表示

html

<button onclick="add()">綁定事件</button>
<button onclick="removeEvent()">解綁事件</button>
<button id="button">點選</button>
           

js

class event {
    constructor(prop) {
        this.element = prop
    }
    handler() {
        console.log(this);
    }
    add() {
        this.element.addEventListener('click', this.handler.bind(this), false);
    }
    destroy() {
        this.element.removeEventListener('click', this.handler, false);
    }
};
const Event = new event(ele)

function add() {
    Event.add();
}
function removeEvent() {
    Event.destroy()
}
           

我在點選綁定事件按鈕後點選最右邊按鈕會正确列印

event

這個類,因為是改變了上下文,但是我點選解綁後再點選右邊按鈕還是會列印,說明我沒有解綁成功,後面查資料就發現綁定和解綁都是隻能使用函數(不能是匿名函數、或者直接

function

)這種的。

add() {
        this.element.addEventListener('click', this.handler);
    }
           

如果這樣寫的話就沒什麼問題了,這樣列印的就是

<button id="button">點選</button>
           

但是實際項目中我就是需要這個

this

怎麼辦呢,也有個辦法,雖然我們沒法解綁,但是我們可以讓他不執行呀

class event {
    constructor(prop) {
        this.element = prop
        this.canClick;
    }
    handler() {
        console.log(this);
    }
    add() {
        this.canClick = true
        this.element.addEventListener('click', this.handler.bind(this), false);
    }
    destroy() {
        this.canClick = false
    }
};
           

這樣也能繞着圈子達到我們的目的,不過就是不那麼好看!!