Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass callback function to a JS class?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading