Knockout 3.2 Components


Version 3.2 of Knockout was released a few weeks ago and it introduces a major new feature: Components and Custom Elements. A big part of this new feature is the support for asynchronously loading views and view models via AMD.

Even if your app doesn't use AMD, the new component feature is worth the upgrade just to help deal with one of the biggest anti-patterns I see in large enterprise-y Knockout apps: templates for complex form fields with way too much logic in HTML.

Before

Here's an example of a "Super Text Field" which does everything from tab indexes to validation to tooltips. It's implemented using the template binding with many parameters which may or may not be used.

JS fiddle

Notice the volume of logic in the HTML template, like adding "txt-" to the id and defaulting the tabindex, which cannot be unit tested and therefore become quite brittle.

After

With Knockout 3.2, we can use the component binding instead to define a ViewModel (constructor function) for the HTML template and render it using a <super-text-field> custom HTML element.

JS fiddle

This may not seem very different but there are some big wins here:

Please note that Knockout isn't forcing you to move your logic into JS. You can still have all that logic in your HTML if you really want and still use the component binding because the viewModel parameter in the component registration is optional. Hopefully though now that Knockout can construct ViewModels for you those messy HTML templates will be a thing of the past.

Check it out

The new component binding in 3.2 is highly configurable and is a great new addition to the library.

[ Archive · Home ]