Two-Way Databinding with Knockout

Earlier this week, I wrote a post about two-way databinding with jQuery. I was looking for a fast & elegant way to do it, but I came up somewhat empty. A lot of what I was finding suggested using a different plug-in or framework, such as Knockout. I decided to give Knockout a whirl, and I’m an instant fan.

My favorite part is how the binding occurs declaratively in the HTML.

<input data-bind="checked: boolValue" type="checkbox" />
<input data-bind="value: textValue" />

That’s all you need to bind the values to the controls–nice, right!? Okay, but this is javascript, so what’s going on at the top? Surely, it’s a mess. Nope, it’s just as easy. Just create a view model and call Knockout’s applyBindings method.

var viewModel = {
    boolValue: ko.observable(true),
    textValue: ko.observable("Hello!")
};
ko.applyBindings(viewModel);

That’s it, I promise. To show that there’s nothing up my sleeve, here’s the entire page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.min.js"></script>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            var viewModel = {
                boolValue: ko.observable(true),
                textValue: ko.observable("Hello!")
            };
            ko.applyBindings(viewModel);
        });
    </script>
</head>
<body>
    <input data-bind="checked: boolValue" type="checkbox" />
    <input data-bind="value: textValue" />
    
    <div>The value of boolValue is <span data-bind="text: boolValue"></span></div>
    <div>The value of textValue is <span data-bind="text: textValue"></span></div>
</body>
</html>

The Knockout site has really good interactive tutorials for getting started. If you’re interested in learning or exploring further, definitely start there.

Advertisements

2 thoughts on “Two-Way Databinding with Knockout”

Leave a comment

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