Click Handler中的范围

时间:2015-08-11 07:19:04

标签: javascript addeventlistener

我有类似以下内容,但我收到错误:" this._toggle不是函数"

function handler(){
  this._toggle();
}
SelectFX.prototype._toggle = function(){
   ...
   this.removeEventListener('click', handler);
}
this.addEventListener('click', handler);

我猜测是与addEventListener创建的范围有关,

我当时认为将此添加到变量会修复但是这段代码:

var self = this;
function handler(){
  self._toggle();
}
SelectFX.prototype._toggle = function(){
   ...
   this.removeEventListener('click', handler);
}
this.addEventListener('click', handler);

但上面给出了错误"无法读取属性' _toggle'未定义"

如果我使用下面的匿名函数作为点击处理程序,它工作正常但我需要稍后删除点击事件,请帮助

SelectFX.prototype._toggle = function(){
   ...
}
this.addEventListener('click', function(){
   this._toggle();  //Works fine but I need to remove this addEventListener later on
});

我在这里使用Full插件https://gist.github.com/grassed/ce76d9b2a5fa6ab9e5be创建了一个Gist,它以this.selPlaceholder.addEventListener为中心('点击',clickHandler);

1 个答案:

答案 0 :(得分:1)

您可以使用本机bind函数在所调用的函数中传递应该表示this的对象。您也可以将其用于事件侦听器。在下面的示例中,我在调用this时将someObject传递给someListener



var el = document.getElementById("clickable-span");

var someObject = {
  clickCount: 0,
  someListener: function(){
    this.clickCount++;
    this.showCount();
    el.innerText = 'Click me again';
  },
      
  showCount: function(){
    document.getElementById('target-span').innerText = 'You clicked ' + this.clickCount + ' time(s)';
  }
}

// use bind to pass in what `this` should refer to in the someListener method
// we want `this` to point to someObject so we can use the clickcount and such
el.addEventListener(
  "click", 
  someObject.someListener.bind(someObject)
);

<button id="clickable-span">Click me</button>
<hr />
<span id="target-span"></span>
&#13;
&#13;
&#13;