Monday, October 14, 2013

KnockoutJS and cross-model communication

I have been playing around with shifting ASP.NET MVC view processing from the server to the client in order to lighten the load on the web server. Doing this isn't really hard, all that you really need to do is have the server render an initial view and have the client request the data it needs via AJAX (MVC) or RESTful (WebAPI) calls back to the server. That's the easy part. Processing that data on the client and turning it into a functioning application with rich interactions is the harder part.

One approach that I have taken recently is to use the KnockoutJS library. In a nutshell, Knockout allows you to create a client-side view model that can be bound to your UI components and have them kept in sync automatically for you using 'data-bind' attributes on your html elements. It has been very easy to learn and has allowed for a fairly rich end-user experience without all of the 'find control, get control value, etc.' drudgery that comes with client-side processing. Take the short, in-browser tutorial to get a feel for how easy it is to get going with this small javascript library (15kb min+gz)!

Knockout supports the ability to bind your model to only a certain portion of your UI, which makes it really easy to build partial views in MVC that encapsulate a single piece of functionality that can be reused in multiple locations within your site. One problem that quickly becomes apparent when doing this is what happens when you have a page/view composed of multiple Knockout view models and you need to communicate between them (such as making an update in one panel and having another panel update simultaneously) without tight-coupling of the view models and breaking their independence?

What I have found recently is a Knockout extension called Knockout-Postbox. This extension allows for a messaging pub/sub mechanism (similar to amplify.js and postal.js) that leverages the existing framework in Knockout but can also be used with other, non-knockout, JS code.

I recommend checking it out and playing with it a little. It looks very promising at the moment for my needs.

No comments: