2016-06-29 122 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()的结果里面的变量可以让你如你所愿做的,你是指的在完全相同对象。