Wednesday, August 27, 2014

Fun with Knockout - observables.

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.)



Fun with Knockout - binding.

Fun with Knockout - binding. 

I started learning Knockout JS - a standalone JavaScript library that implements MVVM design pattern.
I have tons of notes and examples that I've constructed, some of them may or may not resemble to some extent those of the original authors, however they are all mine.

Ever since I discovered JSFiddle I've been trying to port, when possible, all of my examples from Visual Studio to JSFiddle for easy sharing. The first that I'd like to present is how to bind data and text fields using knockout and constrast that with binding through jQuery.

Let's create a JavaScript object to represent a stock:

 var stock = {
            cusip: 12345,
            symbol: "MSFT",
            name: "Microsoft",
            bid: 45.92,
            ask: 46.99
        };

To simply bind and display the text for cusip all we need to do is:
<span data-bind="text: cusip">
For values it's just slightly different:
<input data-bind="value: bid" />

and instruct the knockout to perform the bindings for us:
ko.applyBindings(stock);
and that is pretty much the gist of it.

 I have a fully working example posted on the JSFiddle. (note that I'm using bootstrap for nice formatting.)

Screenshots: