So I have the following simple ES6 plugin that can be used to change the background of an element (created for demo purpose) :
src/index.js
class changeBGColor {
constructor({ targetBG , triggerEl }) {
this.changeBGElem = document.getElementById(targetBG);
this.triggerElem = document.getElementById(triggerEl);
this.addEventListeners();
//this.onClick = this.onClick.bind(this);
//this.onClick.bind(this);
}
addEventListeners() {
this.triggerElem.addEventListener( 'click' , this.onClick.bind(this) );
}
changeBG() {
const bgChangeBgElem = this.changeBGElem;
bgChangeBgElem.classList.toggle('myclassName');
}
onClick(ev) {
console.log(this);
if( ev.target.hasAttribute('data-changeBG') ) {
this.changeBG();
}
}
}
export default changeBGColor;
And I am using my plugin in my main.js file like so:
src/main.js
import changeBGColor from './index.js';
new changeBGColor({
targetBG : 'changeBGOne',
triggerEl : 'triggerBGOne'
});
new changeBGColor({
targetBG : 'changeBGTwo',
triggerEl : 'triggerBGTwo'
});
Now the problem i have is inside addEventListeners
method, I have the following code:
this.triggerElem.addEventListener( 'click' , this.onClick.bind(this) );
As you can see I use bind()
to bind the scope of this to the class changeBGColor
, but I don't want to do this in this manner.
I want something like:
this.onClick = this.onClick.bind(this); // i don't really know what this does, saw it in another plugin, but somehow , this does't work for me.
The problem is the above doesn't work either. I copied it above solution from a GitHub repository, so my question is why does the above solution not work for me and more importantly what is it really doing because this.onClick = this.onClick.bind(this);
doesn't make sense to me at all, can somebody break this down for me, please.
P.S. I don't want to use arrow functions to circumvent this problem, that works fine, I know.
Here is a working example of the plugin: JSfiddle.