Reputation: 115
I've searched all over the place for an answer to this, and maybe the answer is just that - it doesn't exist, but hoping someone has some magic.
I'm using Knockout to bind several forms on a page. This all works fantastically. However, trying to send these forms to PDF converter has proved a challenge.
The rendered HTML still appears Knockout-y. I've tried to get the rendered DOM with $('body').html() but I still get the HTML tags with data-bind attributes. Is there some way to get the final rendered pure HTML for passing to the PDF converter?
Upvotes: 4
Views: 2777
Reputation: 18051
You can grab the rendered elements before they are added to the DOM in the afterRender event. See http://knockoutjs.com/documentation/template-binding.html#note_3_using_afterrender_afteradd_and_beforeremove for more info.
If you need access to the final rendered elements, create a custom binding (http://jsfiddle.net/nE7kK/):
<body data-bind="getRenderedElements: viewModel">
<ul data-bind="foreach: viewModel">
<li data-bind="text: name"></li>
</ul>
</body>
viewModel = ko.observableArray([
{ name: "Bungle", type: "Bear" },
{ name: "George", type: "Hippo" },
{ name: "Zippy", type: "Unknown" }
]);
ko.bindingHandlers.getRenderedElements = {
update: function (element, valueAccessor) {
// use timeout so browser has time to render the elements
setTimeout(function() {
var html = $(element).html();
alert(html);
}, 1000);
}
};
ko.applyBindings(viewModel);
Note: If you use virtual elements you should tell knockout to allow the getRenderedElements binding access to these elements, see: http://knockoutjs.com/documentation/custom-bindings-for-virtual-elements.html
Upvotes: 2