Storing data in custom events

13 posts

Flag Post

Is is possible to store data in custom events? Like if I have say a UnitEvent, would I be able to somehow store the Unit that the UnitEvent belongs to when I dispatch it?

 
Flag Post

Of course, you just need to include a variable to hold the unit. Something like:

public class UnitEvent extends Event
{
    // The unit responsible for this event
    public var unit:Unit;

    public function UnitEvent(type:String, unit:Unit)
    {
        super(type);
        this.unit = unit;
    }
}
 
Flag Post

Is this a common practice? I might not be looking in the right place, but I don’t see any examples of other events that use variables other than the type.

 
Flag Post

Yep, that is common practice. You need to create your own custom events to store any data you want.

 
Flag Post

Ok then, thanks guys!

 
Flag Post
Originally posted by Arloistale:

would I be able to somehow store the Unit that the UnitEvent belongs to when I dispatch it?

If the Unit itself dispatches the event, it’ll be the target of it.

 
Flag Post

Okay, what if I have two data that I need to take care of in the UnitEvent. The first is completely related to the UnitEvent: the unit itself. The second is a rectangle. When the unit enters the rectangle relative to the stage, I need the event to dispatch. Since the rectangle is unrelated to Units, is it bad practice to store it in the UnitEvent? Should I keep track of it some other way?

 
Flag Post

It’s not unrelated, if the interaction between them matters. You need to make sure that the event’s in a sensible package and that they really should be related, but there’s nothing wrong with having both of them in the event if they need to be together.

 
Flag Post

What disturbs me though is that they won’t always need to be together. The UnitEvent also describes events like if the unit dies or possibly other actions unrelated to rectangles. So if the event type won’t always be about a rectangle, then having a rectangle variable in the unit event would be extra information, which I don’t think is efficient.

 
Flag Post

You can always make multiple events, and have those custom events extend a UnitEvent. Then dispatch the correct event each time.

 
Flag Post

I’d probably let the rectangle dispatch that AreaEvent.ENTER

 
Flag Post

Ahhh that is probably a good way to do it. THanks.

 
Flag Post
Originally posted by Arloistale:

Is this a common practice? I might not be looking in the right place, but I don’t see any examples of other events that use variables other than the type.

Just to note, most events use variables like this. See MouseEvent for example; it has properties for the mouse position, whether the button is clicked etc.