How to: Handle Events in JScript

An event is an action, such as clicking a mouse button, pressing a key, changing data, or opening a document or form, that a user typically performs. Furthermore, program code can also perform an action. An event handler is a method that is bound to an event. When the event is raised, the code within the event handler is executed. JScript .NET event handlers can be connected to events in any type of .NET Framework application (ASP.NET, Windows Forms, console, and so on). However, new events cannot be declared in JScript. Only the events that already exist can be utilized by JScript code.

To create an event handler for a Button control's Click event

  • Add the following code:

    // Events.js
    import System;
    import System.Windows.Forms;
    
    class EventTestForm extends Form
    {
      var btn : Button;
    
      function EventTestForm()
      {
        btn = new Button;
        btn.Text = "Fire Event";
        Controls.Add(btn);
        // Connect the function to the event.
        btn.add_Click(ButtonEventHandler1);
        btn.add_Click(ButtonEventHandler2);
      }
    
      // Add an event handler to respond to the Click event raised
      // by the Button control.
      function ButtonEventHandler1(sender, e : EventArgs)
      {
        MessageBox.Show("Event is Fired!");
      }
    
      function ButtonEventHandler2(sender, e : EventArgs)
      {
        MessageBox.Show("Another Event is Fired!");
      }
    }
    
    Application.Run(new EventTestForm);
    

    Note

    Each event handler provides two parameters. The first parameter, sender, provides a reference to the object that raised the event. The second parameter, e in the example above, passes an object specific to the event that is being handled. By referencing the object's properties (and, sometimes, its methods), you can obtain information such as the location of the mouse for mouse events or data being transferred in drag-and-drop events.

To compile the code

  1. Use the command-line compiler, jsc.exe, provided with Visual Studio.

  2. Type the following command-line directive to create a Windows executable (EXE) program named Events.exe:

    jsc /target:winexe Events.js

    Note

    Raising a single event can result in calling multiple event handlers by linking as many functions to the event as needed:

    btn.add_Click(ButtonEventHandler1); 
    btn.add_Click(ButtonEventHandler2);
    . . .
    

See Also

Tasks

How to: Compile JScript Code from the Command Line

Other Resources

Writing, Compiling, and Debugging JScript Code