Off the Ridge code

Off the Ridge Code Newsletter

Search

Fun with Knockout – observables.

Published August 28, 2014 in knockout - 0Comments

This is continuation of the previous post on knockout, so let’s continue and modify the previous example to include obervable feature, i.e. when the data changes in the input box (go ahead and play with it) then the field (in this case <span>) gets updated automatically without any need for extra JavaScript code or jQuery. 

Previously I defined simple JavaScript object:
 var stock = {
            cusip: 12345,
            symbol: “MSFT”,
            name: “Microsoft”,
            bid: 45.92,
            ask: 46.99
        };

Let’s add observable to it:
 var data = {
                stock: {
                    cusip: ko.observable(12345),
                    symbol: ko.observable(“MSFT”),
                    name: ko.observable(“Microsoft”),
                    bid: ko.observable(45.92),
                    ask: ko.observable(46.99)
                }
            };
Screenshots:
I highlighted the difference between creating non-observable object and observable in knockout.

Once again, fully working example posted on the JSFiddle. (note that I’m using bootstrap for nice formatting.)