Hummingbird allows for easy communication between your application and the UI via several mechanisms - one of them being data binding. See JavaScript integration for another one.
Data binding synchronizes the state of your UI with that of the game, effectively eliminating a lot of JavaScript boilerplate that would otherwise be needed. Data binding is a pretty popular feature in the web world and if you are familiar with angular.js or react.js this feature will be very familiar. However, our data bindings are written in C++ and directly integrated into Hummingbird which means that the system has better performance than any other JavaScript libraries.
As this feature is rather complex let's start with a simple example to make sense of it all.
To start, you need to expose an object (by reference), to the UI. We'll call the exposed C++ object a "model" as it will serve as the backing store of the data.
You can create a named model using the cohtml::View::CreateModel
method:
The cohtml::View::CreateModel
invocation registers a model named g_TestPlayer
which corresponds to the g_Player
C++ instance. The CoherentBind
above it takes care of exporting the player class just like it would with standard binding.
Once the object is exported from C++, it can be attached to the DOM using the set of data-bind-*
properties. To complete the example from above, imagine that we want to move a nameplate in the UI using the player's left position:
Note the special double curly brace syntax ({{expression}}
) that you need to use.
With the model exposed and the HTML using it, the <div>
element is now linked to the player. We aren't done yet though - to save on computation Hummingbird will only update the element if you tell it to do so.
// Somewhere in your game loop void Update() { ... // Change the player: g_Player->SetScore(score); // Tell Hummingbird the player changed: view->UpdateWholeModel(&g_Player); // Finally, tell Hummingbird that now is a good time to synchronize all changes: view->SynchronizeModels(); }
Note that cohtml::View::UpdateWholeModel
only marks the model as dirty but doesn't do any work. The synchronization is done inside cohtml::View::SynchronizeModels
which allows you to call it once for all changes. This improves performance as multiple changes within the same frame won't trigger multiple syncs.
With these 3 simple steps the <div>
will automatically update anytime the model changes. Note that you didn't have to write any JavaScript to synchronize the UI and the game. Although this example is contrived, you can imagine how powerful this feature can become when dealing with a complex screen powered by tens of variables. Scroll below for more details on how to make use of the subsystem.
nullptr
is not supported at the moment, i.e. expressions which are using it won't be updated.The syntax of the data binding attributes is a JavaScript expression. The simplest expressions only refer to the model's properties and are encapsulated in double curly braces like we just saw above:
where myModel
is a named model which has a leftPos
property.
You can also construct complex expressions such as:
Only the code referring to the model's properties needs to be inside the curly braces.
data-bind-value
The data-bind-value
attribute takes a value and assigns the node's textContent
property to it.
Example:
The following attributes allow you to modify the element's style:
Data bind attribute | Affected style property | Accepted values |
---|---|---|
data-bind-style-left | left | string or number (px) |
data-bind-style-top | top | string or number (px) |
data-bind-style-opacity | opacity | floating point number between 0 and 1 |
data-bind-style-width | width | string or number (px) |
data-bind-style-height | height | string or number (px) |
data-bind-style-color | color | CSS color as string or unsigned RGBA |
data-bind-style-background-color | background-color | CSS color as string or unsigned RGBA |
data-bind-style-background-image-url | background-image | URL to the image |
data-bind-style-transform2d | transform | string, containing 6 comma-separated numbers |
data-bind-style-transform-rotate | transform: rotate(..) | string or number (deg) |
All the properties above that take number (px) will assume that the number is a measurement in pixels (e.g. binding 42 to data-bind-style-left
will be equivalent to left: 42px
).
If data-bind-style-transform-rotate
takes a number (deg) then it will assume that the number is a measurement in degrees (e.g. binding 90.5 to data-bind-style-transform-rotate
will be equivalent to transform: rotate(90.5deg)
).
There are two other styling attributes - data-bind-class
and data-bind-class-toggle
. data-bind-class
takes a string in the format data-bind-class="class-name[;class-name]"
. The class name can be any CSS class. The class specified by class-name
will be added to the element. Here's a brief example:
data-bind-class-toggle
takes a string in the format data-bind-class-toggle="class-name:bool_condition[;class-name:bool_condition]"
. The class-name
is the name of some CSS class and bool_condition
is a boolean or an expression that evaluates to a boolean. If the boolean is true
or the condition evaluates to true
, the class specified by class-name
is added to the element, otherwise it is removed.
Let's see an example with class toggling:
The red
class will be present on ToggleWithExpression
as long as {{this.Health}} < 50
is true
, changing the element's background to red. Respectively the red
class will be present on ToggleWithBoolean
as long as {{this.hasLowHealth}}
is true
. Otherwise it won't be applied and the element will have whatever background it usually has.
The attributes above only allow you to modify the visual style and the text content of DOM elements. The real power of the data binding system stems from the fact that you can also modify the entire DOM tree with it. This is done via two other attributes:
data-bind-if
: Displays a DOM element based on a condition. The expressions in the attribute value should evaluate to a boolean value.data-bind-for
: Repeats a DOM node for each element in a collection. The basic syntax is data-bind-for="iter:{{myModel.arrayProperty}}"
, where myModel.arrayProperty
must be an array, and iter
is a variable used for iteration, which is available in data binding attributes for the child DOM nodes. The syntax for accessing properties of an iterator in a data-bind-for
is {{iter.property}}
.You can also use the full form data-bind-for="index, iter:{{myModel.arrayProperty}}"
, where index
is loop counter. If you don't need use the index or iterator you can use _
e.g. data-bind-for="index, _:{{myModel.arrayProperty}}"
If the data-bind-for
collection is a std::vector
then the elements could be also raw
/std::shared_ptr
/std::unique_ptr
pointers (or your custom pointer type).
data-bind-for
with a collection of primitive types is not supported.data-bind-if
attribute will be lost if the expression's value is switching between true and false.data-bind-for
will cause undefined behavior if the collection's size is changed.Structural data binding allows you to generate entire screens by just providing a template for each element in a collection (e.g. all items in the player's inventory) and the system will take of repeating the template as many times as necessary.
The next several examples only show the relevant HTML because the C++ model is straightforward:
The data binding events are dom element attributes for attaching event listeners on the DOM.
Example:
event
- The JavaScript Event object from the fired event.[eventName]
- All events listed in Supported Events. Example: click, mouseup, dblckick, etc.this
- Is set to the DOM element on which the handler is registered.Supported Events
abort: is fired when the loading of a resource has been aborted.
blur: is fired when an element has lost focus
click: is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.
dblclick: is fired when a pointing device button (usually a mouse's primary button) is clicked twice on a single element.
error: is fired when an error occurred; the exact circumstances vary, events by this name are used from a variety of APIs.
focus: is fired when an element has received focus.
focusin: is fired when an element is about to receive focus.
focusout: is fired when an element is about to lose focus.
keydown: is fired when a key is pressed down.
keypress: is fired when a key that produces a character value is pressed down.
keyup: is fired when a key is released.
load: is fired when progression has begun successful.
mousedown: is fired when a pointing device button is pressed on an element.
mouseover: is fired when a pointing device is moved onto the element that has the listener attached or onto one of its children.
mouseout: is fired when a pointing device (usually a mouse) is moved off the element that has the listener attached or off one of its children.
mouseenter: is fired when a pointing device (usually a mouse) is moved over the element that has the listener attached.
mouseleave: is fired when the pointer of a pointing device (usually a mouse) is moved out of an element that has the listener attached to it.
mousemove: is fired when a pointing device (usually a mouse) is moved while over an element.
mouseup: is fired when a pointing device button is released over an element.
input: is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
scroll: is fired when the document view or an element has been scrolled.
touchstart: is fired when one or more touch points are placed on the touch surface.
touchend: is fired when one or more touch points are removed from the touch surface.
resize: is fired when the document view has been resized.
durationchange: is fired when the duration attribute has been updated.
emptied: is fired when the media has become empty.
ended: is fired when playback or streaming has stopped because the end of the media was reached or because no further data is available.
seeked: is fired when a seek operation completed.
seeking: is fired when a seek operation began.
timeupdate: is fired when the time indicated by the currentTime attribute has been updated.
To signify that a model needs updating use cohtml::View::UpdateWholeModel
. It will update all properties of the model, including those that haven't actually changed.
cohtml::View::SynchronizeModels
updates all the models that have been marked to have been changed.
To convert from the C++ values of the properties of the model the cohtml::Property
interface is used. Simple expressions (like data-bind-value="{{g_Player.score}}"
) are converted directly to the C++ type used by Hummingbird for the specific data-bind
operation. This is implemented via the cohtml::Property::ToNumber
, cohtml::Property::ToString
, cohtml::Property::ToBoolean
, cohtml::Property::ToColor
methods. They in turn call the cohtml::CoherentToNumber
, cohtml::CoherentToString
, cohtml::CoherentToBoolean
and cohtml::CoherentToColor
functions. Overloading these functions will allow to convert from your C++ type to a Hummingbird type. For example, to convert from MyColor
to renoir::Color
add
For some of the operations a fallback using CSS value as string is also allowed. For example, when using data-bind-style-color="{{g_Player.color}}
the color
property will be converted to renoir::Color
. In case this conversion fails, it will convert the property to a string and parse the color from that, using the CSS syntax for that value.
Complex expressions are compiled to JavaScript stub functions that evaluate the expression and return the result. This means that the properties of the bound C++ model are converted to JavaScript values and the result is then converted back to a C++ value. This requires several crossings of the C++ <-> JavaScript boundary (one for the function call and one for each property access of the model), which might be quite expensive. The fallback algorithm, described above, is used for values returned from complex expression as well.
Finally, you can unregister models from binding using the cohtml::View::UnregisterModel
API. This removes the model by instance pointer. Unregistration will not remove any elements bound to the model - they'll preserve their last state.
Hummingbird provides a default version of CoherentBind which will error out if you don't provide a template specialization of CoherentBind for your type. In some cases you might want to implement the default by yourself (e.g. binding all types via the reflection system of your engine). To do that you need to declare a template specialization for cohtml::IsDefaultBindEnabled
structure in the way shown below.
For example let's declare DisableDefaultBinding
specialization for user-defined type Player
:
In the case you need to write a more generic version, you can use the second template parameter where you can use SFINAE and enable_if techniques. If you wish to disable default binding for classes and unions you can write something similar to this:
In case you need to know when your data binding model was updated/synchronized (e.g. you want to run some JavaScript on model changes), you can implement your own events similar to the following: