What is Knockout.js?
Salient features of this library are:
- Declarative bindings. A way to bind UIs to underlying data model using declarative bindings like data-bind=”text: firstName”
- Dependency tracking. The build in dependency tracking updates the right UI when the underlying data changes by doing dependency check.
What is MVVM?
Model-View-ViewModel is a design pattern for building user interfaces.
- Model: an application’s persisted data.
- View: an application’s visible, interactive UI component.
- ViewModel: In MVVM ViewModel is the an abstract layer to separate View and Model. ViewModel is a code based representation of data and operations on a UI.
To bind this to UI, data-bind attribute are used like:
For binding view to viewmodel, call Knockout.js activateBindings method as given here:
To automatically update UI when the data model changes, we need to use Knockout’s observable as given below:
- text : use text binding to display text value
- html : use html binding to display HTML
- css : use css binding to add or remove CSS classes
- style : use style binding to add or remove style values to the DOM node
- attr : use attr binding to
- visible : use visible binding to control the DOM element’s visibility
- foreach : use foreach to loop around array and create markup on them
- if : use if to control a section of markup’s visibility
- ifnot : similar to if binding but works if the conditional is false
- with : use with in templates for creating new binding context
- click : use click binding to add an event handler to the click event to elements like a, input and buttons
- event : use event binding to add an event handler to specified events like mouseover, mouseout, keypress, keydown etc. on the DOM element
- submit : use submit binding to add an event handler to the DOM node which would be called when the element value is being submitted like in case of form submit
- enable : use enable binding to enable the DOM element based on the specified boolean expression. This is typically used for DOM elements like input, select, textarea.
- disable : use disable binding to disable the DOM element based on the specified boolean expression
- value : use value binding to link the DOM element’s value with a property in view model. Typically used with input, select, textarea
- hasfocus : use hasfocus binding to link a DOM element’s focus state with a property in view model
- checked : use checekd binding with checkbox or radio button to link it with property on view model
- options : use options binding to control the options of a select control (<select>)
- selectedOptions : use selectedOptions binding to control the elements selection in a multi-select list. Use this with <select> element and options binding
- uniqueName :
- template : use template binding to render a templates output to the associated DOM element
In addition to the built-in bindings, knockout.js supports creating custom bindings.