Introducing Knockout JS to my Studio
Knockout JS—a.k.a. Knockout (KO)—gives me the final HTML-5 era solution to developing all of my user interfaces—under JavaScript, Silverlight or WPF—with the same pattern, MVVM. With KO, there is no need to respond to successful AJAX calls with lines of code that attach events to DOM elements related to the call. We can now declare these events and continue to use jQuery templates! KO makes my working life simpler because I can think in terms of MVVM for all of my UI work.
There is no need for me to sell KO—it sells itself. Just check out the homepage and see that MIX11 video. What remains are my first impressions of KO as I use in my redesign of kintespace.com (yes, finally underway!):
KO Workflow
It looks like a KO-based job goes like this:
- Layout static elements in HTML/CSS.
- Define jQuery templates for JSON-driven elements.
- Declare KO data-binding attributes on static elements and templates.
- Back declarations with page-level script with KO View Model, the apply bindings call (
ko.applyBindings(myViewModel);
) and$(window.document).ready
function block.It’s that “ready” block that will make the first call to the KO View Model. It’s the View Model that is the bulk of my code.
Interesting Points
Some interesting points:
- My View Model object can contain
$.getJSON
AJAX calls and still keep a clean separation between “UI logic” and the data-centeredness of the View Model. This is achieved by calling external “UI logic” procedures after a successful AJAX call—defining custom jQuery events makes this even more decoupled. - The
afterRender
declaration for KO-based jQuery template binding provides a way to format DOM elements from a template after they have loaded. Not knowing when the document is “ready” (in terms of jQuery) is a problem with usingafterRender
is—so I add adocumentIsReady
KO “observable” to my View Model and use it in theafterRender
function. - I still have a need for plain jQuery templates without KO declarations. This is need is the equivalent of the desire for One-Time data binding in WPF/Silverlight.