Changes between Version 9 and Version 10 of SimulationSyntax


Ignore:
Timestamp:
Dec 15, 2009, 10:51:14 PM (14 years ago)
Author:
Philip Taylor
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • SimulationSyntax

    v9 v10  
    267267== Defining component types in JS ==
    268268
     269Now 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
     272function ExampleTwo() {}
     273
     274ExampleTwo.prototype.Init = function() {
     275    ...
     276};
     277
     278ExampleTwo.prototype.Deinit = function() {
     279    ...
     280};
     281
     282ExampleTwo.prototype.OnUpdate = function(msg) {
     283    ...
     284};
     285
     286Engine.RegisterComponentType(IID_Example, "ExampleTwo", ExampleTwo);
     287}}}
     288
     289This 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
     293The `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
     295Instead 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
    269299...
    270 
    271 == Defining a new message type ==