无法使用javascript删除事件侦听器

时间:2016-06-29 14:01:25

标签: javascript event-listener

请告诉我,为什么removeEvent不起作用,并在调用removeEventListener后单击body工作。我只是让它变得更加简单,以便更好地理解 p - 具有属性和方法的对象;
p.is_open - 真/假属性;
p.switcher - DOM元素;

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';
};

我可以用另一种方式解决这个问题,但我想解决这个问题。 感谢。

1 个答案:

答案 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()方法会创建一个 new 函数,该函数在调用时将其this关键字设置为提供的值[...]。

以下是一个例子:

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()的结果存储在变量中可让您按照自己的意愿进行操作,并且您正在引用完全相同的对象。