In this blog, I will create a simple example to demonstrate how knockout javascript library can be used to create observable properties.
Let's say we want to create an example where we can easily compute the temperature in celcius and fahrenheit. Knockout makes it really easy due to the observable and compute in-built features. Let's look at the code first:
In this code, the HTML part is pretty simple. We have 2 input boxes which are data bound to 2 properties namely cel and fah. In the javascript code, we first create a viewmodel which has cel as an observable property. What this means is that change notification would be available for this property. Then we create another property named fah which is a compute property. This means that the value of fah is computed based on change notifications somewhere else. In the ko.computed method we are providing the read, write and owner properties. Whenever cel is changed Read is called. In the read method we just update the value of fah based on cel value. If you change the value in the fah input box itself, write is called. In our case, write is updating the value of cel anytime fah is changed.
Now anytime any of the input boxes is changed, the value in other box will automatically get updated.
Let's say we want to create an example where we can easily compute the temperature in celcius and fahrenheit. Knockout makes it really easy due to the observable and compute in-built features. Let's look at the code first:
In this code, the HTML part is pretty simple. We have 2 input boxes which are data bound to 2 properties namely cel and fah. In the javascript code, we first create a viewmodel which has cel as an observable property. What this means is that change notification would be available for this property. Then we create another property named fah which is a compute property. This means that the value of fah is computed based on change notifications somewhere else. In the ko.computed method we are providing the read, write and owner properties. Whenever cel is changed Read is called. In the read method we just update the value of fah based on cel value. If you change the value in the fah input box itself, write is called. In our case, write is updating the value of cel anytime fah is changed.
Now anytime any of the input boxes is changed, the value in other box will automatically get updated.