Read here working with Knockout.js Part 2: Understanding MVVM
Read here Getting started with Knockout.js
So far we have learnt basics of Knockout.js. In last two posts we tried to understand need of KO and MVVM pattern.
One of the most essential and important feature of MVVM is, “When View Model changes View must be notified such that UI will be refreshed automatically”
In Part 2 we created ViewModel as following. This is a simple ViewModel and would not notify View on changes of the property’s value.
var studentViewModel = { studentName: "DJ", studentGrade: "B", studentMarks: 90 }
To enable automatic notification from ViewModel to View, we need to make properties of ViewModel as an OBSERVABLE PROPERTIES
We can make a property Observable as following
So we can rewrite StuentViewModel with automatic notification as following
var studentViewModel = { studentName: ko.observable('DJ'), studentGrade: ko.observable('B'), studentMarks: ko.observable(90) }
Now whenever value of property changes in the ViewModel View will be notified and UI will be refreshed automatically.
There is no need to change anything at View side. Different View Elements are now subscribed to ViewModel properties. Now whenever value at ViewModel will be changed , View will be notified.
<body> <span data-bind="text:studentName"></span> <span data-bind="text:studentGrade"></span> <span data-bind="text:studentMarks"></span> <script> ko.applyBindings(studentViewModel); </script> </body>
We can read and write from observable using JavaScript getter and setter. A observable value can be read as following
We can write to observable as following
So now you see how much easier it is in KO to autmetically refresh UI on the chnages in ViewModel. Only we need to make ViewModel property as observable. I hop you find this post useful. In next post we will learn about Compound Observables. Thanks for reading.
Leave a Reply