Data binding syntax
Knockout’s declarative binding system provides a concise and powerful way to link: the View with the ViewModel, we can think basically it binds javascript variables to fields”
A binding consists of two items separated by a colon: “the binding name” and “value”. Check the list of declarative bindings.
1 2 3 |
... data-bind="text: myFooMessage"" ... |
Binding values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!-- variable (usually a property of the current view model --> <div data-bind="visible: shouldShowMessage">...</div> <!-- comparison and conditional --> The item is <span data-bind="text: price() > 50 ? 'expensive' : 'cheap'"></span>. <!-- function call and comparison --> <button data-bind="enable: parseAreaCode(cellphoneNumber()) != '555'">...</button> <!-- function expression --> <div data-bind="click: function (data) { myFunction('param1', data) }">...</div> <!-- object literal (with unquoted and quoted property names) --> <div data-bind="with: {emotion: 'happy', 'facial-expression': 'smile'}">...</div> |
Difference between: text and value
Difference between data-binds: text (one direction = text) and value ( bi directional = value). Make sense that the data-bind=”value:xxx” can be use only with input tag. In the case of data-bind=”text:xxx” on any tag because is going to just “display information” on only one direction
Declarative binding object literals
Several declarative binding Object Literal
Computed members
What if you have got an observable for name, and another for subname, and you want to display the full name? That’s where computed observables come in
Observable Arrays
If you want to detect and respond to changes on one object, you’d use observables. If you want to detect and respond to changes of a collection of things, use an observableArray
Multiple bindings
An element can include multiple bindings (related or unrelated), with each binding separated by a comma.
1 2 |
<!-- related bindings: valueUpdate is a parameter for value --> Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" /> |
Bindings without a value
Knockout 3.0+
1 |
<span data-bind="text">Text that will be cleared when bindings are applied.</span> |
Create a new custom binding (ko.bindingHandlers)
All binding handlers should have two functions: init and update.
Both functions get five parameters, of which the first two are the most important. You will probably use these two all the time and the other three very rarely.
The first is the element on which the binding is applied, and the second is the value accessor function which returns the bound value
The “init” function is called when the bindings are applied and “update” function is called every time when the referred observables are changed and also right after the init function.