Rob Huxley
Rob Huxley

Reputation: 33

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);
    }

Upvotes: 2

Views: 123

Answers (1)

Ashish Patil
Ashish Patil

Reputation: 4604

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.

Upvotes: 1

Related Questions