Skip to content

Example: Creating and Managing Events

jsutlive edited this page May 17, 2023 · 2 revisions

Working with events

Events make it simple to manage the relationships between the model (simulation data backend), view (render/GUI), and control (mouse/key input) layers of the system while reducing the amount of potential "spaghetti code". This framework uses an adaptation of Danilow's C# Like Event Handlers Pattern.

Create an event

To create an event, you need to create an EventHandler object, designating one data type to be transferred using the event. Since EventHandler is a generic class, this parameter must be placed within angle brackets on the left side of the assignment. See examples here:

public class MyEventClass{

     public EventHandler<Boolean> onPressedButton = new EventHandler<>();
     public EventHandler<Integer> onNumberChanged = new EventHandler<>(); 
     public EventHandler<Component> onChangeComponent = new EventHandler<>();
}

Subscribe/ unsubscribe to an event

To subscribe to an event, find a method in your subscribed class whose inputs match the data type for the event. Referencing our class from earlier on the page, we will now make a new class and call this event. Notice the syntax of the method call. To unsubscribe

public class MySubscriberClass{

    MyEventClass event;

    public MySubscriberClass(){
        event = new MyEventClass();
        event.onPressedButton.subscribe(this::actionA);
    }

    void actionA(boolean b){
         //do stuff
    }

    void unsubscribeFromMethod(){
         event.onPressedButton.unSubscribe(this::actionA)
    }
}

Close an event

If an event is no longer needed, such as during object deletion or program shutdown, you can close the event to save memory usage.

     public EventHandler<Boolean> onPressedButton = new EventHandler<>();
     
     onPressedButton.close();

Clone this wiki locally