3

Is there any way to render from a html string in knockout?

i.e

var html = ko.renderFromString('<p data-bind="text:name"></p>', {name:"Fred"});

It would be very convenient for what I'm doing.

$(".container").append(html);
$(".container").on("click", "p", function(e){
console.log(ko.dataFor(this));});
2
  • Have you seen this article? knockmeout.net/2011/10/… It describes not exactly what you want but you could get some ideas from it. Commented Jan 16, 2014 at 6:02
  • Yes basically what you want is templating. You can also use the html binding, but in that case the viewmodel would already be bound. Commented Jan 16, 2014 at 8:44

1 Answer 1

7

If you're reluctant on messing with the Template Engines, try this:

ko.renderFromString = function (html, data)
    {
    var node = new DOMParser().parseFromString(html, "text/html");
    this.applyBindings(data, node.body);
    var res = node.body.innerHTML.toString();
    this.cleanNode(node);
    delete node;
    return res;
    };

It basically creates a temporary (in-memeory) DOM element from your Html string, binding your data, returning the innerHTML of the bound element then discarding it.

Sign up to request clarification or add additional context in comments.

5 Comments

exactly what I wanted to accomplish.
Not bad 10000 in 7270ms I was getting 3869ms for a simple string.replace function I was using - but this opens up a lot more to me - thanks.
When are you calling dataFor()?
After I append the generated string to the dom and handle a delegated click event. I've added the code to the question
That's because i'm calling this.cleanNode(node); and delete node; in the renderFromString function (as i didn't know you're going to use that binding later, i thought it's only the render results you're interested in), try to remove this lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.