Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

javascript - KnockoutJS: Using 'html' binding, new elements not binding

I have a view model which contains a ko.observable representing the conent of a div, like so:

function claimContainerViewModel(elem, api) {
    this.content = ko.observable('<somecontent>');
}

At some later time, I update that content using an AJAX call, and I have a div with the following binding:

<div id="ClaimContainer" data-bind="html: content">

The HTML returned for 'content' has data-bind's of it's own, and this is the issue: None of those bindings are being parsed. According to Knockout, and every source I've read, this is supposed to happen. When using the 'html' binding, KO is supposed to be smart enough to do a re-bind.

Is this a bug in KO 2.2.0 (the version I am stuck with right this very second), or am I misinterpreting how the html binding handler works? And before anyone asks, no applyBindings will not work in this case, because the container uses an html bind, which applyBindings assumes is supposed to handle the re-bind itself (I've confirmed this by stepping down in to KO's code).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE:

This is the final version of my custom binding. This now works automatically, doesn't doubly bind, and works just like the 'html' binding, but more dynamic.

if (!ko.bindingHandlers['dynhtml']) {
    ko.bindingHandlers['dynhtml'] = {
        'init': function() {
            return { 'controlsDescendantBindings': true };
        },
        'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
            ko.utils.setHtml(element, valueAccessor());
            ko.applyBindingsToDescendants(bindingContext, element);
        }
    };
}

Please, please, PLEASE be aware that this can be unsafe if you don't know the source of your HTML. Very, very unsafe. If unsanitized user input can ever make it in to your HTML, this could be a huge security hole, so watch out for cross site scripting attacks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...