Data binding
last updated on: 03/23/17
| tags: bindings, data, service, readdata, writedata, source
## Binding
Bindings present a means to allow elements of the view to communicate with the code running behind the view, the data-context, or even with a remote data source directly. Bindings can be bidirectional, i.e. from the source to the target and from the target to the source, and one-directional, which go only from the source to the target.
### Two way bindings
<!-- How is a manual two way binding implemented? -->
The standard two-directional binding is implemented with the [bind] keyword. In the markup, we can declare a [data-bind-...] attribute, and typically we will bind to the value of an input tag in order to be able to update the source from the target.
```html
<div data-class=someClass>
<input type="text" data-bind-val="{bind path=$someProperty}" />
</div>
```
In the code above, the value of the input field will be set to the initial value of the property [someProperty]. If the user modifies or inputs a different value in the text field, then upon calling the view's function 'updateSources()' the source will be updated to the value from the input field. This will be an example of a manual two-way binding.
<!-- What is an automatic binding, and how is it implemented? -->
If the property bound to the input field's value is active, then it will be possible to automatically update the source. This is illustrated in the code bellow:
```html
<div data-class=someClass>
<input type="text" data-bind-val="{bind path=$someProperty writedata=change}" />
</div>
```
It is useful to note that [writedata] can accept more than one argument. For example, we can have 'writedata=change,keyup,input'. Similarly, we can ensure automating updating of the target by using [readdata]. This way every time the property is updated, the view will be updated as well.
```html
<div data-class=someClass>
<input type="text" data-bind-val="{bind path=$someProperty readdata=$someProperty_changed}" />
</div>
```
### One way bindings
<!-- What is a read, one way binding -->
Often we only need to create one way binding, which goes from the source to the target. This is done in cases when we simply need to display data that comes from an external data source or the code and we do not need to modify it directly. In these situations we use the [read] keyword when creating the binding. We also bind to the text node of the element and therefore can render the text in most of the DOM elements.
```html
<div data-class=someClass>
<span data-bind-text="{read path=$someProperty}"></span>
</div>
```