Binding expressions

In this section we will look at how binding is defined, the different kinds of bindings and how they affect the UI.

There are typically three kinds of binding.

  • One way – flowing data from the binding context to the UI
  • Two way – flowing data to and from the UI and the binding context
  • Once – this mechanism mirrors one-way binding, but it occurs solely during the UI parsing phase. It’s crucial to understand that the data being referenced should already exist on the context prior to the parsing process. Should the property on the context undergo any change post-parsing, the UI will remain unaffected since no observers have been established to track such alterations.

It’s essential to understand that binding doesn’t impact attributes. Binding assigns the property to the targeted element. To set attributes, one should use attribute binding.

Data Flow

The blue arrows indicate the flow of data based on the binding type.

Once binding

<element property.once="property_path"></element>

One way binding

<element property.one-way="property_path"></element>

Two way binding

<input value.two-way="property_path"/>

In the given example, ‘value’ is a property of the HTMLInputElement. Additionally, inputs possess a “change” event that enables bi-directional data flow.

Bind

<input value.bind="property_path" />
<element property.bind="property_path"></element>

Bind is a tool that streamlines the binding process, making it unnecessary to distinguish between one-way and two-way bindings. By using “.bind”, it automatically selects the right binding mode. Two-way binding is associated with inputs and requires a “change” event. For custom elements, you can simulate this by dispatching a change event. Most elements have one-way binding since they aren’t user-modifiable. Although “.one-way” and “.two-way” options exist, opting for “.bind” is often more convenient. However, when it comes to custom elements, the scenario differs. It’s not always clear if an element will trigger a “change” event. In such situations, being explicit is advisable. When you set up a two-way binding on a custom element, it implies that the element will emit a change event when that property alters.

Text Content

Binding to an element’s text content is quite common, and this is where the intricacies of expression evaluation often emerge. Consider the sentence: “John Doe is 20 years old” from the given example.

<div>${person.firstName} ${person.lastName} is ${person.age} old</div>

This is a one-way binding and updated each time one of the properties change.