knockoutjs : Computed Observables

  • COMPUTED OBSERVABLES – FUNCTIONS DEPENDENT ON ONE OR MORE OTHER OBSERVABLES.
  • What if you’ve got an observable for firstName, and another for lastName, and you want to display the full
    name? That’s where computed observables come in – these are functions that are dependent on one or
    more other observables, and will automatically update whenever any of these dependencies change.
    Your evaluator function will be called once each time any of its dependencies change, and whatever value you return will be passed on to the observers such as UI elements or other computed observables.

    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Home Page</title>
    <script src="../lib/knockout-3.2.0.debug.js" type="text/javascript"></script>
    </head>
    <body>
    	<label>Hello </label>
    	<input type="text" data-bind="value: fullName" />
    	<script type="text/javascript">
    		// Here's my data model
    		var viewModel = {
                firstName: ko.observable("Shiv"),
                lastName: ko.observable("Yadav")
            };
            viewModel.fullName = ko.dependentObservable(function () {
                // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
                return viewModel.firstName() + " " + viewModel.lastName();
            });
    		ko.applyBindings(viewModel); // This makes Knockout get to work
    		
    		setTimeout(function(){ viewModel.firstName("Shivanshu"); }, 3000);// change data after 3 seconds
    		
    	</script>
    </body>
    </html>
    

    ang4

    After 3 seconds….

    ang5

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s