jQuery Templates are fantastic! They provide an easy way to render your data from JavaScript to HTML.
I’ve written a simple jQuery.tmpl() implementation on JSFIDDLE to show the basics.
It is also easy to use nested templates to simplify rendering and to repeat the template over the contents of an array. Another example displays a nested template using an array of objects.
jQuery Templates also provides a mechanism for updating the data that is rendered out.
However, this feature has a problem. In this sample, I have made the “update” button dynamic using jQuery. But go ahead and click it and see what happens. It loses the cool styling and hover events. Why? Because jQuery.tmpl re-renders it’s templates and REPLACES the version on the page with a new one when you call .update();
So, jQuery.tmpl doesn’t keep the connections to your cool UI Widgets. That’s a hassle, but not too bad.
It does get bad when the user starts interacting with your template-rendered HTML. Imagine a page where there is a list of items, that can be expanded when the user wants to see details. Imagine also that the user can enter information into fields for each item. Then the user hits the sort button.
BAM! The template gets re-rendered. All the user’s expansions are lost. All the user’s entries are lost. AND you still have to reconnect all your widgets. Nasty.
Now, here’s my advice. When you have a programming problem that’s all nasty and thorny…don’t write code! Programming is easy because there are people much smarter than us that have already written the solutions for most problems.
Templates have a problem. jQuery doesn’t fix it. I’m sure somebody else has solved this problem. Let’s find them.
Today the answer is knockout.js by Steve Sanderson.
Our problem is that while jQuery.tmpl makes it easy to go from JavaScript to HTML, it does nothing for going from HTML to JavaScript. Knockout encapsulates jQuery.tmpl and extends it to provide the full round trip.
Read the excellent documentation, check out the live samples, and listen to Steve’s interview with Scott Hanselman
I’ve made the ‘Hello World‘ sample from the Knockout.js site available on JSFIDDLE, go and play with it a bit, and see what you can make it do.