• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • Knockout

Custom Observable in Knockout JS

  • Yatendrasinh Joddha
  • July 8, 2017
  • 2 minute read
knockoutjs
Total
0
Shares
0
0
0

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 same as observable but with our own functionality.

Why it is required to create custom observable?

Here, I would like to discuss about 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 all ok but suddenly I started facing 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 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

String

After applying numericObservable

Number

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>

 

Yatendrasinh Joddha
Yatendrasinh Joddha

I have healthy knowledge and experience in Azure, O365 and ASP.Net with c#, MVC, WebApi along with client-side frameworks and libraries like JavaScript, JQuery, KnockoutJs, AngularJs, Angular, ReactJs, NodeJs

Views: 3,889

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • Getting Started with AWS Step Functions: Orchestration Made Simple

    Getting Started with AWS Step Functions: Orchestration Made Simple

    4 months ago
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    2 years ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    3 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

 

Loading Comments...
 

    %d