I have an application that builds a small page upon load, which presents the user with navigation options. When the user selects a navigation option, the page creates an object representing the ViewModel of the selected navigation option, then gets the corresponding HTML from the server and places it inside of a div.
My expectation is that I could get the HTML, use a Knockout HTML binding to put it into the div (wrapped in a container div with a preselected ID), then bind the container div to the ViewModel.
However, I get errors when I try to do this. This seems very much in line with what Knockout is supposed to do, so I'm a little puzzled about what I'm doing wrong. Any help would be much appreciated.
I have created a fiddle to encapsulate the problem (clicking the links does nothing):
Here's the HTML:
<body>
<div id="container">
<div id="menu">
<ul data-bind="foreach: modules">
<li><a href="#" data-bind="click: $root.goTo.bind($data), text: $data"></a></li>
</ul>
</div>
<div id="body" data-bind="html: curBody">
</div>
</div>
</body>
And the JavaScript:
function GlobalVM() {
var self = this;
self.curVM = ko.observable();
self.test = ko.observable('test');
self.curBody = ko.observable('body');
self.modules = ko.observableArray();
self.goTo = function(module) {
if (module == 'Test1') {
self.curVM(new SubVM1());
self.curBody('<div id=\'realbody\' data-bind=\'text: curVM().test1\'></div>');
ko.applyBindings(self, document.getElementById('realbody'));
}
if (module == 'Test2') {
self.curVM(new SubVM2());
self.curBody('<div id=\'realbody\' data-bind=\'text: curVM().test2\'></div>');
ko.applyBindings(self, document.getElementById('realbody'));
}
};
self.initialize = function() {
self.modules.push('Test1');
self.modules.push('Test2');
};
}
function SubVM1() {
var self = this;
var test1 = ko.observable('test1');
}
function SubVM2() {
var self = this;
var test2 = ko.observable('test2');
}
var vm = new GlobalVM();
vm.initialize();
ko.applyBindings(vm);
templatebinding and using anobservableto store the template name. That will let Knockout handle the bindings automatically. - ebohlman