Tags
The purpose of knockout.js is to bind UI elements to underlying data model so changes made are updated to model immediately and vice versa. So compared to traditional javascript code where element values are explicitly set through code knockout relies on binding mechanism. It uses a declarative approach where the elements on the page are bound to properties of an ViewModel object.
Two main principles of Knockout are Observables and Bindings.
Scenario 1:
A sample one-way data bind to display text will look like the following
At high level the step(s) for the above are:
- Reference knockout.js
- Use data-bind attribute indicating the property name of the object. In the example above it is authorName
- Initialize a viewModel object with a single property authorName value set to ‘Girish Srinivasa’
- Use applyBindings methods passing in the viewModel object
Scenario 2:
In the following example the authorName property of the ViewModel object is changed when the the value in the text box is changed.
- data-bind=”text…” will render a label control
- data-bind=”value…” associated with <input tag will render a text box control
Change the value in text box control to Girish Srini and notice that the label still displays Girish Srinivasa
This is because there is notification to indicate that the ViewModel object property authorName requires updating. This can be corrected by the using observables that will have ViewModel object properties automatically updated as shown in the following snap shots.
On Initial Load
After changing the value in the text box