|
| 1 | +# Custom events |
| 2 | + |
| 3 | +Custom events are automatically validating the arguments the client send via a client event. Everything that is possible with custom events can also be created via ```Alt.OnPlayerEvent```. |
| 4 | + |
| 5 | +Custom events are registered via ```Alt.On(eventName, delegate)```. The delegate can have any signature and the module checks when a event occurs if the signature of the delegate fits the event arguments the client sends. |
| 6 | + |
| 7 | +For custom events you can't use the lambda operator because it needs to know the parameter types. |
| 8 | + |
| 9 | +Here is a very basic sample that expects just a single ```string``` from a client event named ```myMessage```. |
| 10 | + |
| 11 | +We register it via ```Alt.On```. We need to help the compiler a bit by defining the method parameter types for the generic method. The types are defined from left ro right same as in the method definition itself. |
| 12 | + |
| 13 | +```csharp |
| 14 | +Alt.On<IPlayer, string>("myMessage", MyMessageHandler); |
| 15 | +``` |
| 16 | + |
| 17 | +And the method is defined as this. |
| 18 | +```csharp |
| 19 | +public void MyMessageHandler(IPlayer player, string message) |
| 20 | +{ |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +The method will be called like this from client |
| 25 | +```js |
| 26 | +alt.emitServer("myMessage", "my test message"). |
| 27 | +``` |
| 28 | + |
| 29 | +The method name doesn't really matter in this case and i just named it similar to the event name. |
| 30 | + |
| 31 | +Supported parameter types are ```object```, ```bool```, ```int```, ```long```, ```uint```, ```ulong```, ```float```, ```double```, ```string```, ```IPlayer``` (or any types extending IPlayer), ```IVehicle``` (or any types extending IVehicle), ```Dictionary<string, (any type listed here)```, ```Alt.Function```, any type listed here as array e.g. int[]. |
| 32 | +Also any dictionary in dictionary, array in array, ect. endless depth types are supported, because they are resolved recursively. |
| 33 | + |
| 34 | +## Dictionaries |
| 35 | + |
| 36 | +Any js object send via ```alt.emitServer``` will be a dictionary. |
| 37 | + |
| 38 | +```csharp |
| 39 | +Alt.On<IPlayer, string>("myBigObject", MyBigObjectHandler); |
| 40 | +... |
| 41 | +public void MyBigObjectHandler(IPlayer player, Dictionary<string, string> myBigObject) |
| 42 | +{ |
| 43 | + if(!myBigObject.TryGetValue("eyeColor", out var eyeColor)) return; |
| 44 | + Console.WriteLine($"EyeColor: {eyeColor}"); |
| 45 | +} |
| 46 | +``` |
| 47 | +And this is the client code. |
| 48 | +```js |
| 49 | +const myBigObject = {firstName:"John", lastName:"Doe", eyeColor:"blue"}; |
| 50 | +alt.emitServer("myBigObject", myBigObject); |
| 51 | +``` |
| 52 | + |
| 53 | +When you use ```object``` as a parameter, or type in dictionary, it will accept any type and you can manually check which type it is. |
0 commit comments