I have created a little class in JS to handle buttons across a site i’m building. When creating a new instance of a Button i want to be able to pass a callback function.
Currently i’m creating the instance like this: (Class code follows below)
import Button from './scripts/button';
const btn = document.getElementById('test');
new Button(btn);
What i want to do is something like this:
import Button from './scripts/button';
const btn = document.getElementById('test');
new Button(btn, function() {
console.log('im clicked');
});
The code for the Button class looks like this:
class Button {
constructor(el) {
this.element = el;
}
/*
more to come here, but this is to simplify stuff
*/
}
export default Button;
How would i do this?
>Solution :
You’ll need to add the callback to the constructor(), and then call it within the constructor, so it looks like:
constructor(el, cb) {
this.element = el;
cb();
}