Event system
The event system is at the core of MTA scripting. Events work closely in conjunction with the element tree. Events are triggered when something happens - a player enters a marker, an element is clicked on etc. Each event has a source element, this is the element that performed the action.
Event handlers
To use the event system, you attach event handlers to elements in the element tree using addEventHandler. When you do this, your function will get triggered for all the events triggered on that element, it's parents (and their parents, etc.) and it's children (and their children). As such, an event handler attached to the root element will be triggered when an event occurs for any element. As a consequence you should generally use as specific a handler as you can. If you wish to just see when the player enters a specific marker, just attach the event handler to that marker.
Each event handler has two 'hidden' variables:
- source: This is the element that the event originated from.
- this: This is the element that the handler is being triggered on (i.e. the one you attached it to with addEventHandler).
Built in events
MTA has a number of built in events. These are listed on the pages Client Scripting Events and Scripting Events.
Custom events
You can create your own events that can be triggered across all resources. This is an important way to communicate with other resources and allow them to hook into your code. To add your own custom event, just call the addEvent function. You can then use the triggerEvent function to trigger that event any time you want - either using a timer, or based on a more general event.
For example, you could be making a Capture the Flag game mode and want to trigger an event when a player captures the flag. You could do this by attaching a event handler to the standard MTA onMarkerHit event and checking that the player entering the marker has the flag. if they do, you can then trigger your more specific onFlagCaptured event and other resources could handle this as they please.
Canceling
Events can be canceled with cancelEvent. This can have a variety of effects, but in general this means that the server will not perform whatever action it would usually do. For example, canceling onPickupUse would prevent a player being given what they tried to pick up, canceling onVehicleStartEnter would prevent the player entering the vehicle. You can check if the currently active event has been canceled using wasEventCanceled.