Coherent GT
A modern user interface library for games
Data-binding for JavaScript

Coherent GT allows you to use JavaScript instead of C++ for the purposes of data-binding. See Data Binding for the C++ part.

Why use JavaScript for data-binding at all?

Data-binding JavaScript values lets you create the UI without any C++. For example, you can:

  • Using for mocking purposes if the Backend isn't implemented yet, the UI programmer can finish the whole UI using only JavaScript, CSS and HTML.
  • Registering data models that are coming from AJAX requests.

Working with pure JavaScript Types

The API is mostly the same as in the C++ version. You start by registering a JavaScript model by calling engine.createJSModel(modelName, model).

For example:

engine.createJSModel('player', {
maxHealth: 100,
currentHealth: 50,
heroType: 'warrior',
pet: {
type: 'dog'
traits: [{
strength: 10,
intelligence: 20
}, {
strength: 15,
intelligence: 17

This would create a global variable player with the given properties. We can use this model with data-binding attributes like:

<div data-bind-value="{{player.currentHealth}}"></div>
<div data-bind-for="trait:{{player.traits}}">
<div data-bind-template="trait" data-bind-model="{{trait}}"></div>
<script type="text/html" data-bind-template-name="trait">
<div data-bind-value="{{this.strength}}"></div>
<div data-bind-value="{{this.intelligence}}"></div>

For more information about the data-binding attributes: Data Binding

To update the JavaScript models we use similar functions like the C++ - engine.updateWholeModel(model). This function only tells GT that this model has changed. To force an update of the data-bound values (update the DOM) you must also call engine.synchronizeModels.

Hybrid JavaScript Types with C++ Types

Another usage of JavaScript models is to extend an already existing JS object, exposed from C++, with new properties. Start by callingengine.extendModel(model, additionalProperties). For example:

// If the player object is already registered from the C++ code with properties name and health
// {name: 'Joe', health: 50}
engine.extendModel(player, {
height: 1.80,
items: [{
itemName: 'hammer',
power: 15
}, {
itemName: 'javelin',
power: 10

This would add the properties 'height' and 'items' to the model player, then we can easily use them for the data-binding:

// Property from C++
<div data-bind-value=”{{player.name}}”></div>
// Property from JavaScript
<div data-bind-value=”{{player.height}}”></div>

Update and synchronization is done in exactly the same way like pure JavaScript models (engine.updateWholeModel/engine.synchronizeModels):


Important: Don't extend a model with an object/array property that already exists.

// Changing the object property like this won't work.
player.pet = { type: 'cat'};
// Instead you can do this:
player.pet.type = 'cat';