| 269 | Now we want a JS implementation of `ICmpExample`. Think up a new name for this component, like `ExampleTwo` (but more imaginative). Then write '''`binaries/data/mods/public/simulation/comonents/ExampleTwo.js`''': |
| 270 | {{{ |
| 271 | #!js |
| 272 | function ExampleTwo() {} |
| 273 | |
| 274 | ExampleTwo.prototype.Init = function() { |
| 275 | ... |
| 276 | }; |
| 277 | |
| 278 | ExampleTwo.prototype.Deinit = function() { |
| 279 | ... |
| 280 | }; |
| 281 | |
| 282 | ExampleTwo.prototype.OnUpdate = function(msg) { |
| 283 | ... |
| 284 | }; |
| 285 | |
| 286 | Engine.RegisterComponentType(IID_Example, "ExampleTwo", ExampleTwo); |
| 287 | }}} |
| 288 | |
| 289 | This uses JS's ''prototype'' system to create what is effectively a class, called `ExampleTwo`. (If you wrote `new ExampleTwo()`, then JS would construct a new object which inherits from `ExampleTwo.prototype`, and then would call the `ExampleTwo` function with `this` set to the new object. "Inherit" here means that if you read a property (or method) of the object, which is not defined in the object, then it will be read from the prototype instead.) |
| 290 | |
| 291 | `Engine.RegisterComponentType` tells the engine to start using the JS class `ExampleTwo`, exposed (in template files etc) with the name `"ExampleTwo"`, and implementing the interface ID `IID_Example` (i.e. the `ICmpExample` interface). |
| 292 | |
| 293 | The `Init` and `Deinit` functions are optional. Unlike C++, there are no `Serialize`/`Deserialize` functions - each JS component instance is automatically serialized and restored. (This automatic serialization restricts what you can store as properties in the object - e.g. you cannot store function closures, because they're too hard to serialize. The details should be documented on some other page eventually.) |
| 294 | |
| 295 | Instead of `ClassInit` and `HandleMessage`, you simply add functions of the form `On`''`MessageType`''. When you call `RegisterComponentType`, it will find all such functions and automatically subscribe to the messages. The `msg` parameter is usually a straightforward mapping of the relevant `CMessage` class onto a JS object (e.g. `OnUpdate` can read `msg.turnLength`). |
| 296 | |
| 297 | == Defining a new message type == |
| 298 | |