Papa's Perspective

2 Great JavaScript Data-Binding Libraries

JavaScript libraries help you build powerful, data-driven HTML5 apps.

Data binding is one of the best features of XAML, so it's no surprise that this functionality has become more popular in HTML5. Several great JavaScript libraries help bring common and often-used patterns to HTML5/JavaScript development. Two of my favorite libraries that add data-binding features are Knockout JS, and JsRender with JsViews. There are others, but these are the two I've found most useful and they make it a lot more fun for me to write HTML5 apps with JavaScript.

Why You Should Get KO'd
Knockout, developed by Steve Sanderson and available via NuGet, is inspired by Model-View-ViewModel (MVVM) style patterns. It has been around for more than a year and has a very active community. The community has even developed popular plug-ins for Knockout, such as KnockoutJS Mapper, which you can use to map JSON directly into a JavaScript object. Simply put, Knockout allows the binding of a JavaScript object to an HTML page.

In data binding, the concept of observables refers to objects and properties that can notify the UI elements when their values have changed. Knockout builds on this concept by requiring objects and properties to be defined with a custom function named observable. Once you understand that you need to create observable properties and not just plain JavaScript properties, the rest falls into place.

There are three basic things you need to perform data binding with Knockout, after you link to the Knockout script file:

1. A JavaScript object whose properties are ko.observables:

var vm = { person : { 
        firstName: ko.observable("John"),
        lastName: ko.observable("Papa")
    }
};

2. HTML elements with declarative binding syntax:

First Name: <input data-bind=
  "value: person.firstName"/><br/>
Last Name: <input data-bind=
  "value: person.lastName"/><br />
Full Name is 
<span data-bind=
  "text: person.firstName"><span/> 
<span data-bind=
  "text: person.lastName"><span/>

3. Knockout to apply the bindings between the object and the HTML elements:

$(document).ready(function () {
    ko.applyBindings(vm);
});

This is a trivial example but it really emphasizes the simplicity of the data binding with Knockout. With just a few lines of code, the values in the JavaScript object are pushed to the corresponding HTML elements. When the applyBindings function is called, Knockout binds the object named vm to the page. Knockout then looks for any elements that have the data-bind attribute. When it finds them, it sees that they're pointing to an object name person.firstName and person.lastName. Notice that the page is bound to the vm object, which becomes the data context for the page. This is why the elements can reference properties directly on the vm object, such as person.

Knockout can do much more including: creating dependent observables (such as a calculated property), templating and binding handlers (which are similar to behaviors in XAML). Starting with version 2.0.0, Knockout supports templating with its own native templates or you can use plug-in templating libraries. The previous example could be rewritten using a template:

<script id="personTmpl" 
  type="text/x-jquery-tmpl">
<div>
  First Name: <input data-bind=
    "value: person.firstName" /><br/>
  Last Name: <input data-bind=
    "value: person.lastName" /><br/>
  Full Name is
  <span data-bind=
    "text: person.firstName"></span> 
  <span data-bind=
    "text: person.lastName"></span>
</div>
</script>

<div id="personContainer" data-bind=
  "template: 'personTmpl'"></div>

Knockout's native templates support defining templates in any DOM element. This means a template could be defined in a standard div if so desired, instead of in a script tag. This just scratches the surface of what it supports, but the key thing to remember is that it's easy to get started and once you do, there's a lot of power under the hood if you need it. And if you get stuck, there's a great community that's accessible from the Knockout Web site.

Updated Approach to jQuery Templates
JsViews and JsRender are the vision of Boris Moore. Combined, these libraries offer data binding and templating that can be used with or without MVVM patterns. JsViews handles the data-binding functionality while JsRender adds powerful templating capabilities. Boris offers a great history of JsViews and JsRender in his Dancing with Data blog. He explains the roadmap and why he expects these libraries to replace jQuery Templates.

Like Knockout, JsViews hinges on the concept of observables. However, it implements the observability in a slightly different manner. This is best demonstrated through code. Let's rewrite the example using JsViews and JsRender:

<script id="personTmpl" 
  type="text/x-jquery-tmpl">
<div>
  First Name: <input data-getfrom=
    "[person.firstName]" data-to=
    "[person.firstName]" /><br/>
  Last Name: <input data-getfrom=
    "[person.lastName]"  data-to=
    "[person.lastName]"/><br/>
  Full Name is 
  <span data-getfrom="[person.firstName]" /> 
  <span data-getfrom="[person.lastName]" />
</div>
</script>

<div id="personContainer"></div>

JsViews uses the HTML data-getfrom and data-to attributes instead of the data-bind attributes. The big difference here is that you can specify both directions of the binding. The data-getfrom indicates where the HTML element will get its data from, while the data-to indicates where the value is sent. These bindings could come from and go to different objects, for example. Because the final two bindings are inside of span tags and are read only, they only use the data-getfrom attribute. The data-binding syntax is also slightly different from Knockout. JsViews wraps the binding property with square brackets whereas Knockout defines a binding as the target and source properties separated by a colon.

The JavaScript that JsViews uses is pretty similar to Knockout except that it doesn't require the properties to be defined as observables. Instead, JsViews handles the observability under the covers.

$(document).ready(function () {
  $("#personContainer").link(vm, 
    "#personTmpl");
});

var vm = { person : { 
    firstName: "John",
    lastName: "Papa"
  }
};

JsRender and JsViews were not yet in beta (at press time), so some syntax might have changed. Both libraries are expected to reach beta in the first half of 2012. However, the libraries are already gathering a following. I like the syntax of JsViews because it requires fewer JavaScript changes and it doesn't make me modify my JavaScript objects. Knockout, which has been around longer, has a great community as well.

Data-Driven HTML5 Apps
Both Knockout and JsViews with JsRender have a clean syntax, fit with the MVVM pattern (or other client-side separation patterns), and are quite powerful. Which one you use really depends on your preference, because both JavaScript libraries support all of the key ingredients such as binding, declarative syntax, templating and separation patterns. And for those times when libraries often take you almost all the way there, neither library leaves you hanging as they both let you inject custom code.

If you're building HTML5 applications, you should seriously consider taking a good look at these data-binding libraries. Using libraries such as Knockout or JsViews with JsRender makes it easier to write and maintain powerful data-driven HTML5 applications.

About the Author

John Papa is a Microsoft Regional Director and former Microsoft technical evangelist. Author of 100-plus articles and 10 books, he specializes in professional application development with Windows, HTML5, JavaScript, CSS, Silverlight, Windows Presentation Foundation, C#, .NET and SQL Server. Check out his online training with Pluralsight; find him at johnpapa.net and on Twitter at twitter.com/john_papa.

comments powered by Disqus

Featured

Subscribe on YouTube