简体   繁体   中英

Scope of this in Click Handler

I have something similar to the following but I get the error: "this._toggle is not a function"

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

which I'm guessing is to do with the scope that addEventListener creates,

I would of thought then that adding this to a variable would fix but this code:

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

But the above gives the error "Cannot read property '_toggle ' of undefined"

If I use an anonymous function like below for the click handler it works fine but I need to Remove the Click Event later on, please help

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

I've create a Gist here with the Full plugin https://gist.github.com/grassed/ce76d9b2a5fa6ab9e5be which centers around this.selPlaceholder.addEventListener( 'click', clickHandler);

You can use the native bind function to pass the object that should represent this in the function called. You can use that also for event listeners. In the example below, I pass in someObject to be this when someListener is being called.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM