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

Please help me understand code under "handleEvent" method below in Javascript

< button id = "elem" > Click me < /button>

  <
  script >
  class Menu {
    handleEvent(event) {
      // mousedown -> onMousedown
      let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
      this[method](event);
    }

    onMousedown() {
      elem.innerHTML = "Mouse button pressed";
    }

    onMouseup() {
      elem.innerHTML += "...and released.";
    }
  }

let menu = new Menu();
elem.addEventListener('mousedown', menu);
elem.addEventListener('mouseup', menu); <
/script>

Could someone please help me understand what’s going in this section of the code? Thank you.

 handleEvent(event) {
       // mousedown -> onMousedown
       let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
       this[method](event);
    }

>Solution :

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

event.type[0].toUpperCase()  -- this will return first character of your event name in upper case.(e.g. for submit event, it will return `S` )

event.type.slice(1) -- this will return you all characters of event name except first character.  (e.g. for submit event , it will return `ubmit`)

Then you are concatinating above with on.

After that in last line of function, you are calling derived function which you generated from above string e.g. onSubmit.

In your case, it looks like you are capturing mousedown event & then converting that event to onMousedown() string & calling your onMousedown() method.

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