Whole trick is around rebinding your view. ko
does not allow to call applyBindings
twice on the same node, so you need to cleanNode
from bindings and apply it to element.
Here is the working scenario:
function myViewModel() {
let self = this
self.htmlTemplate = ko.observable();
self.initialize = function ()
{
self.htmlTemplate(`
<p data-deId="de-box-5" data-bind="html: myViewModel().getDynamicContent()">
Initial content
</p>
`);
};
self.getDynamicContent = function()
{
return "dynamic content";
};
return self;
};
const vm = myViewModel();
const root = $('.xyz-template');
ko.applyBindings(vm, root[0]);
vm.initialize();
const templateHolder = root.find('p');
ko.cleanNode(templateHolder[0]);
ko.applyBindings(vm, templateHolder[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="xyz-template" data-bind="html: htmlTemplate"></div>
Keep in mind that in your particular case you cannot rebind root because everytime you initialize binding html
binding from xyz
div
kicks in, so again <p>
is somehow detached
Here you will also find better ways to solve that problem knockout custom html binding
Code which I posted is just to show the concept