Introduction
Knockout JS is famous and widely used for its two-way binding concept. While developing application we uses ko.observable() to declare a knockout object. Here we will discuss how to create our own custom observable which will work the same way as observable but with our own functionality.
Why it is required to create custom observable?
Here, I would like to discuss a scenario where I choose to create my own observable.
While developing one application I created one observable which was intended to store numeric value, and I used to store that numeric value in database using WebApi. It was going okay but suddenly I started facing a typecasting error while storing that value using my WebApi, then I realized that the value I am passing is in string format. This was happening because I started taking value from user using Textbox which always gives me the value in string format. So, I decided to create my own observable which will always have numeric value even it is coming from Textbox.
Let’s create our own numericObservable
Look at the below Before and After outputs
Before applying numericObservable
After applying numericObservable
Below is the code which will create your personalized observable
- ko.numericObservable = function (initialValue) {
- var actual = ko.observable(initialValue);
- var result = ko.dependentObservable({
- read: function () {
- return actual();
- },
- write: function (newValue) {
- var parsedValue = parseFloat(newValue);
- actual(isNaN(parsedValue) ? newValue : parsedValue);
- }
- });
- return result;
- };
Use below code to declare your own numericObservable
- self.Number = ko.numericObservable();
Full example,
- <html>
- <head>
- <title> </title>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
- </head>
- <body>
- <div id="MainDIV">
- <input type='text' data-bind="value: Number"/>
- <input type='button' data-bind="click: checkType" value='Check'/>
- </div>
- <script>
- ko.numericObservable = function (initialValue) {
- var actual = ko.observable(initialValue);
- var result = ko.dependentObservable({
- read: function () {
- return actual();
- },
- write: function (newValue) {
- var parsedValue = parseFloat(newValue);
- actual(isNaN(parsedValue) ? newValue : parsedValue);
- }
- });
- return result;
- };
- var KOModel = function () {
- var self = this;
- self.Number = ko.numericObservable();
- self.checkType = function(){
- alert(typeof (self.Number()));
- };
- }
- ko.applyBindings(KOModel, document.getElementById('MainDIV'));
- </script>
- </body>
- </html>
Summary
Using this example you can create your custom observable of any type.