AfterRender for html binding

Is there a way to run custom code after Knockout has added html to the DOM and finished rendering? I need this so that I can bind a nested view model to dynamically added html code.

Something like:

<div data-bind="html: dynamicHtml, afterRender: customCode"></div> ... MyViewModel.prototype.customCode = function(){ ko.applyBindings(self.MyInnerViewModel(), document.getElementById('someTagInTheDynamicHtml')); }; 

afterRender is not called here (does it work only with template binding?), and user binding does not help either, because the " update " event cannot be called after updating the DOM.

+7
source share
1 answer

Yes, afterRender only works with template binding.

But you can create your own binding handler that tracks html binding changes and triggers a callback when the value is updated. My example:

 ko.bindingHandlers.afterHtmlRender = { update: function(el, va, ab){ ab().html && va()(ab().html); } } 

Shortened parameter names: va - valueAccessor, ab - allBindings.

Also, the markup should look like this (binding name changed):

 <div data-bind="html: dynamicHtml, afterHtmlRender: customCode"></div> 

http://jsfiddle.net/dDDjf/

Update

Simplified binding code with explanations:

 ko.bindingHandlers.afterHtmlRender = { update: function(element, valueAccessor, allBindings){ // check if element has 'html' binding if (!allBindings().html) return; // get bound callback (don't care about context, it ready-to-use ref to function) var callback = valueAccessor(); // fire callback with new value of an observable bound via 'html' binding callback(allBindings().html); } } 
+12
source

All Articles