Share via


Handling Events

Many elements in a DHTML program can trigger events. The com.ms.wfc.html package uses the same event model as the com.ms.wfc.ui package. If you are familiar with that mechanism, you'll find little difference between the two. A button is a good example. Suppose you want to handle the event that occurs when a user clicks a button on a page. Here's how:

    
public class Class1 extends DhDocument
{
   Class1() { initForm();}
   DhButton myButton = new DhButton();
   private void initForm()
   {
      add(myButton);
      myButton.addOnClick(new EventHandler(this.myButtonClick));
   }
   void myButtonClick(Object sender, Event e)
   {
      ((DhButton) sender).setText("I've been clicked");
   }
}
   

In this code, whenever the button triggers the onClick event (that is, when it is clicked), the myButtonClick event handler is called. The code inside the myButtonClick event handler does very little in this example. It just sets the caption on the button to new text.

Most events propagate all the way up a containment tree; this means that the click event is seen by the button's container and by the button itself. Although typically programmers handle events in the container closest to the event, this event bubbling model can be useful in special cases. It provides the programmer with the flexibility to decide the best place to code the event handlers.

Many different events can be triggered by elements in DHTML, and you can catch them all in the same way. For example, to determine when the mouse is over a button, try the following code, which catches mouseEnter and mouseLeave events for the button:

  
public class Class1 extends DhDocument
{
   DhButton button = new DhButton();
   private void initForm()
   {
      button.addOnMouseEnter(new MouseEventHandler(this.buttonEnter));
      button.addOnMouseLeave(new MouseEventHandler(this.buttonExit);
      setNewElements( new DhElement[] { button } );
   }
   void buttonEnter(Object sender, MouseEvent e)
   {
      button.setText("I can feel that mouse");
   }

   void buttonExit(Object sender, MouseEvent e)
   {
      button.setText("button");
   }
}
   

All events that can be triggered (and caught) are defined in the event classes, based on com.ms.wfc.core.Event.