Introduction:

In this article we will explain how to use computed observables in knockoutjs or what is computed observables in knockoutjs or how to combine one or more property by using computed observables in knockoutjs with example.


Description:

KnockoutJS Computed Observable is a function which is dependent on one or more Observables and will automatically update whenever its underlying Observables (dependencies) change. Suppose you have firstname and lastname you want to display the fullName then we create fullName computed observables property when user make any changes in firstname or lastname then fullName will update automatically whenever any of these dependencies change.

Syntax:

      this.fullName= ko.computed(function(){
            ...
            ... //  function code
            ...
        },this);

 

  • Example:

Let us see below example which demonstrates use of Computed Observables:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>http.Post</title>
    <script src="/Scripts/jquery-3.1.1.js"></script>
    <script src="/Scripts/knockout-3.4.1.js"></script>  
</head>
<body>
    <div class="container">       
        <p>Enter first Name: <input data-bind="value:firstName" /></p>
        <p>Enter Last Name: <input data-bind="value:lastName" /></p>
        <p>Your FullName : <span data-bind="text:fullName"></span></p>
    </div>
    <script>
        function ViewModel() {
            var self = this;
            self.firstName = ko.observable('');
            self.lastName = ko.observable('');
            self.fullName = ko.computed(function () {
                return self.firstName() + " " + self.lastName();
            });
        }
        ko.applyBindings(new ViewModel());
    </script> 
</body>
</html>

 

  • Output:

Let's carry out the following steps to see how the above code works:

o    Save the above code in index.htm file.

o    Open this HTML file in a browser.

o    Enter firstname and lastname in text boxes and see that fullname is automatically updated.

KnockoutJS-Computed Observables

I hope this article will help to you.


0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like