Javascript: / Home / ClassEvents

Class Event Handlers

A class can be defined that assigns the event handlers required for that class. It can also contain the event handler methods. This way all the code needed for that class is contained and protected inside the class.

An object's contained objects, methods and properties are called "members". This is because they belong to the object and can only be used by first specifying the object name, then a dot "." and then the contained member name. As in: titleObject.AddEvents().

Members inside the class are used by adding the "this" keyword. As in this.TitleClick(). Also notice that the addEventListener method requires the name of the event handler method to call the "bind" method. This is to make sure the event handler in the object is called correctly.

    // Code in IntroToJS.js file.
    class LJCTitleClass
    {
      AddEvents()
      {
        pageTitle.addEventListener("click", this.TitleClick.bind(this));
      }
    }

    <script>
      let titleObject = new LJCTitleClass();
      titleObject.AddEvents();
    </script>
<- TitleClass
14ClassEvents