KnockoutJS & ASP.NET Mvc Partial View Loading
Recently I’ve needed to dynamically load ‘partial views’ that are bound to KnockoutJS view models. The application is a single page app approach, composite application where I’m loading a particular view.
Retrieving the ‘partialView’ is rather simple with ASP.NET Mvc:
This is rather straightforward. I make the call to retrieve the template with a jQuery ajax call:
I create my viewmodel, and my viewmodel has a property with the partialViewName defined – ie. self.partialViewName = “_SomePartialView”;
This works very well so far – I have some caching of the html partial, although I might remove this and just takes a more server side ‘get’ ‘varybyparam’ caching on the controller action.
Previously I had an approach like this:
<div data-bind=”with: myViewModel”>
Which I still believe works good for one or two scenarios – but the number of viewmodel objects (I have 20+ views here getting loaded) let me change my approach to more of a ‘load on demand’. I’m pretty happy with this!
Update: one of my concerns that I meant to research and apply here is the impact of loading vm’s to the same dom node with applyBinding and memory leaks.
A good response to this on stack overflow: http://stackoverflow.com/questions/10048485/how-to-clear-remove-observable-bindings-in-knockout-js/10049722#10049722
So what I do for this is use the ko.cleanNode prior to re-applying this binding to the same node: