Off the Ridge code

Off the Ridge Code Newsletter

Search

Fun with Knockout – binding.

Published August 28, 2014 in knockout - 0Comments

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: