2016-06-29 48 views
1

請告訴我,爲什麼removeEvent無法正常工作,並且在removeEventListener被調用後單擊正文工作。我只是讓它更容易理解
p - 我的對象具有屬性和方法;
p.is_open - true/false屬性;
p.switcher - DOM元素;使用javascript無法刪除事件偵聽器

function MyClassname(){ 
    ....... 
    p.switcher.onclick = function(e){ 
    if(p.is_open){ 
     p.close(); 
     document.body.removeEventListener('click', p.close.bind(p)); 
    }else{ 
     p.open(); 
     document.body.addEventListener('click', p.close.bind(p)); 
    }; 
    e.stopPropagation(); 
    }; 
    ....... 
}; 
....... 
MyClassname.prototype.close = function(){ 
    var p = this; 
    p.is_open = false; 
    p.switcher.className = 'closed'; 
}; 
MyClassname.prototype.open = function(){ 
    var p = this; 
    p.is_open = true; 
    p.switcher.className = 'open'; 
}; 

我可以用另一種方式解決這個問題,但我想解決這個問題。 謝謝。

+0

您必須將'p.close.bind(p)'保存在一個變量中。像'var closeHandler = p.close.bind(p);',在你的函數MyClassname()裏面。然後,執行'document.body.addEventListener('click',closeHandler);''和document.body.addEventListener('click',closeHandler);'。使用'.bind()'方法創建一個具有相同主體的**新**函數。因此,它不能刪除,因爲**新**功能從未添加。每次運行'.bind()',它都是一個全新的對象。嘗試運行'var a = function(){}; console.log(a.bind(a)=== a.bind(a));'在瀏覽器的控制檯上。 –

+0

明白了,非常感謝。 – WeekendMan

+0

不客氣。然後我會將它轉換成答案。 –

回答

0

您不能刪除事件偵聽器,因爲您必須將p.close.bind(p)存儲在變量中。
事情是這樣的:

function MyClassname(){ 
    var closeHandler = p.close.bind(p); 
    ....... 
    p.switcher.onclick = function(e){ 
    if(p.is_open){ 
     p.close(); 
     document.body.removeEventListener('click', closeHandler); 
    }else{ 
     p.open(); 
     document.body.addEventListener('click', closeHandler); 
    }; 
    e.stopPropagation(); 
    }; 
    ....... 
}; 
....... 
MyClassname.prototype.close = function(){ 
    var p = this; 
    p.is_open = false; 
    p.switcher.className = 'closed'; 
}; 
MyClassname.prototype.open = function(){ 
    var p = this; 
    p.is_open = true; 
    p.switcher.className = 'open'; 
}; 

p.close.bind(p)西港島線創建一個新功能相同體。
這是一個全新的對象。並且比較2個不同的對象返回false

部分引用MDN約the .bind() method

bind()方法創建一個新的功能,調用它時,有該關鍵字設置爲提供的值[...]。


下面是一個例子:

var button = document.getElementsByTagName('button')[0]; 
 

 
var handler = function(){ 
 
    console.log('click'); 
 
    //this refers to the button 
 
    this.removeEventListener('click', handler.bind(this)); 
 
}; 
 

 
button.addEventListener('click', handler.bind(button));
<button>Click me</button>

正如你所看到的,點擊停留在那裏。再舉一例:

var button = document.getElementsByTagName('button')[0]; 
 

 
var handler = (function(){ 
 
    console.log('click'); 
 
    //this refers to the button 
 
    this.removeEventListener('click', handler); 
 
}).bind(button); 
 

 
button.addEventListener('click', handler);
<button>Click me</button>

存放.bind()的結果裏面的變量可以讓你如你所願做的,你是指的在完全相同對象。