An overview to Knockout

By | 26 August, 2013

When developing an application, traditionally we were used to mix HTML code with Javascript (jQuery) to render the data coming from an Ajax call. However the result of doing this is a bunch of code which is not very readable and maintainable.

To try to overcome this situation several frameworks have come up. They’re the so-called MVVM Frameworks. Knockout is one of the main examples.

Using Knockout the separation of concerns becomes neater, helping developers to organize and structure better their code.

On one hand it’s very true or at least, in my opinion,  Knockout is not simple to catch up with. It introduces new syntax and concepts like dynamic binding between Models and Views. On the other hand, the benefits are worthwhile.

<html>
<head>
 <meta charset="UTF-8">
 <meta name="author" content="Eugenia Pérez, eugenia_perez@cuatrovientos.org">

 <title>Knockout Example 1</title>
 <script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
 <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
 <script type="text/javascript">
   $(function () {
     var viewModel = {
      name: ko.observable("Eugenia"),
      changeName: function () {
      this.name("Maria");
    },
    nameVisible: ko.observable(true)
  };

  viewModel.displayName = ko.computed(function () {
      return this.name() + " is " + (this.nameVisible() ? "visible" : "not visible");
  }, viewModel);

  ko.applyBindings(viewModel);
 });
 </script>
</head>
<body style="">
  Name:
  <input type="text" data-bind="value: name, valueUpdate: 'afterkeydown'">
  <input type="checkbox" data-bind="checked: nameVisible">
  <p>
   Hello, <span data-bind="text: name, visible: nameVisible">Eugenia</span>
  </p>
  <p>
  <span data-bind="text: displayName"></span>
  </p>
  <button data-bind="click: changeName">Change name</button>
</body>
</html>

The previous example shows a ViewModel (kind of objects use by Knockout) with some properties and functions.

The real advantage that Knockout offers is that every time the model changes the view does as well. And what’s more, this happens writing much less code than before. So if you do not believe me just copy and paste the code above and run it in your favorite browser. You will discover the magic of Knockout.

By Eugenia Pérez
Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.